/**
 * Copyright (c) 2006-2012, JGraph Ltd
 */
/**
 * 构造一个新的图形编辑器UI。
 * 创建编辑器用户界面的主控制器，管理所有UI组件和交互。
 *
 * @param {Editor} editor - 编辑器实例，如果为null则自动创建
 * @param {Element} container - UI容器的DOM元素，默认为document.body
 * @param {boolean} lightbox - 是否启用灯箱模式
 */
EditorUi = function (editor, container, lightbox) {
    mxEventSource.call(this);

    this.destroyFunctions = [];
    this.editor = editor || new Editor();
    this.container = container || document.body;

    // 获取图形编辑器实例，用于后续配置和操作
    var graph = this.editor.graph;
    graph.lightbox = lightbox;
    this.initialDefaultVertexStyle = mxUtils.clone(graph.defaultVertexStyle);
    this.initialDefaultEdgeStyle = mxUtils.clone(graph.defaultEdgeStyle);

    // 使用CSS变换可以实现更快的滚轮缩放
    if (graph.useCssTransforms) {
        this.lazyZoomDelay = 0;
    }

    // 预加载子菜单图片，如果支持则替换为嵌入式图片
    if (mxClient.IS_SVG) {
        mxPopupMenu.prototype.submenuImage = '';
    } else {
        new Image().src = mxPopupMenu.prototype.submenuImage;
    }

    // 预加载连接图片
    if (!mxClient.IS_SVG && mxConnectionHandler.prototype.connectImage != null) {
        new Image().src = mxConnectionHandler.prototype.connectImage.src;
    }

    // 在无边框模式下禁用图形和强制平移
    if (this.editor.chromeless && !this.editor.editable) {
        this.footerHeight = 0;
        graph.isEnabled = function () {
            return false;
        };
        graph.panningHandler.isForcePanningEvent = function (me) {
            return !mxEvent.isPopupTrigger(me.getEvent());
        };
    }

    // 创建用户界面
    this.actions = new Actions(this);
    this.menus = this.createMenus();

    if (!graph.standalone) {
        this.createDivs();
        this.createUi();
        this.refresh();

        // 禁用HTML和文本选择
        // 创建文本编辑检测函数，用于控制是否允许文本选择
        var textEditing = mxUtils.bind(this, function (evt) {
            if (evt == null) {
                evt = window.event;
            }

            return graph.isEditing() || (evt != null && this.isSelectionAllowed(evt));
        });

        // 在非编辑状态且无对话框显示时禁用文本选择
        if (this.container == document.body) {
            this.menubarContainer.onselectstart = textEditing;
            this.menubarContainer.onmousedown = textEditing;
            this.toolbarContainer.onselectstart = textEditing;
            this.toolbarContainer.onmousedown = textEditing;
            this.diagramContainer.onselectstart = textEditing;
            this.diagramContainer.onmousedown = textEditing;
            this.sidebarContainer.onselectstart = textEditing;
            this.sidebarContainer.onmousedown = textEditing;
            this.formatContainer.onselectstart = textEditing;
            this.formatContainer.onmousedown = textEditing;
            this.footerContainer.onselectstart = textEditing;
            this.footerContainer.onmousedown = textEditing;

            if (this.tabContainer != null) {
                // 鼠标按下事件用于拖拽和放置
                this.tabContainer.onselectstart = textEditing;
            }
        }

        // 在编辑时使用内置的上下文菜单
        if (!this.editor.chromeless || this.editor.editable) {
            // 允许在提示中的链接显示上下文菜单
            // 创建链接处理函数，专门处理提示中的链接点击事件
            var linkHandler = function (evt) {
                if (evt != null) {
                    var source = mxEvent.getSource(evt);

                    if (source.nodeName == 'A') {
                        while (source != null) {
                            if (source.className == 'geHint') {
                                return true;
                            }

                            source = source.parentNode;
                        }
                    }
                }

                return textEditing(evt);
            };

            if (mxClient.IS_IE && (typeof (document.documentMode) === 'undefined' || document.documentMode < 9)) {
                mxEvent.addListener(this.diagramContainer, 'contextmenu', linkHandler);
            } else {
                // 允许在图形和侧边栏之外显示浏览器上下文菜单
                this.diagramContainer.oncontextmenu = linkHandler;
            }
        } else {
            graph.panningHandler.usePopupTrigger = false;
        }

        // 在给定的面板中包含主要的图形实例
        graph.init(this.diagramContainer);
        // 改进内置编辑器的行换行
        if (mxClient.IS_SVG && graph.view.getDrawPane() != null) {
            var root = graph.view.getDrawPane().ownerSVGElement;

            if (root != null) {
                root.style.position = 'absolute';
            }
        }

        // 创建悬停图标
        this.hoverIcons = this.createHoverIcons();

        // 移动单元格时隐藏悬停图标
        if (graph.graphHandler != null) {
            var graphHandlerStart = graph.graphHandler.start;

            graph.graphHandler.start = function () {
                if (ui.hoverIcons != null) {
                    ui.hoverIcons.reset();
                }

                graphHandlerStart.apply(this, arguments);
            };
        }

        // 当鼠标悬停在滚动条上时添加工具提示，显示空格+拖拽平移选项
        mxEvent.addListener(this.diagramContainer, 'mousemove', mxUtils.bind(this, function (evt) {
            var off = mxUtils.getOffset(this.diagramContainer);

            if (mxEvent.getClientX(evt) - off.x - this.diagramContainer.clientWidth > 0 ||
                mxEvent.getClientY(evt) - off.y - this.diagramContainer.clientHeight > 0) {
                this.diagramContainer.setAttribute('title', mxResources.get('panTooltip'));
            } else {
                this.diagramContainer.removeAttribute('title');
            }
        }));

        // ESC键隐藏对话框，添加空格+拖拽平移功能
        var spaceKeyPressed = false;

        // 覆盖悬停图标，在按下空格键时禁用
        var hoverIconsIsResetEvent = this.hoverIcons.isResetEvent;

        this.hoverIcons.isResetEvent = function (evt, allowShift) {
            return spaceKeyPressed || hoverIconsIsResetEvent.apply(this, arguments);
        };

        this.keydownHandler = mxUtils.bind(this, function (evt) {
            if (evt.which == 32 /* Space */ && !graph.isEditing()) {
                spaceKeyPressed = true;
                this.hoverIcons.reset();
                graph.container.style.cursor = 'move';

                // 按下空格键后禁用滚动条滚动
                if (!graph.isEditing() && mxEvent.getSource(evt) == graph.container) {
                    mxEvent.consume(evt);
                }
            } else if (!mxEvent.isConsumed(evt) && evt.keyCode == 27 /* Escape */ ) {
                this.hideDialog(null, true);
            }
        });

        mxEvent.addListener(document, 'keydown', this.keydownHandler);

        this.keyupHandler = mxUtils.bind(this, function (evt) {
            graph.container.style.cursor = '';
            spaceKeyPressed = false;
        });

        mxEvent.addListener(document, 'keyup', this.keyupHandler);

        // 强制为中键和右键鼠标按钮启用平移
        var panningHandlerIsForcePanningEvent = graph.panningHandler.isForcePanningEvent;
        graph.panningHandler.isForcePanningEvent = function (me) {
            // 在Mac上的FF浏览器中，Ctrl+左键被报告为右键
            return panningHandlerIsForcePanningEvent.apply(this, arguments) ||
                spaceKeyPressed || (mxEvent.isMouseEvent(me.getEvent()) &&
                    (this.usePopupTrigger || !mxEvent.isPopupTrigger(me.getEvent())) &&
                    ((!mxEvent.isControlDown(me.getEvent()) &&
                            mxEvent.isRightMouseButton(me.getEvent())) ||
                        mxEvent.isMiddleMouseButton(me.getEvent())));
        };

        // Ctrl/Cmd+Enter应用编辑值，但在Safari中Ctrl+Enter会创建新行
        // (Enter创建新段落，Shift+Enter停止编辑)
        var cellEditorIsStopEditingEvent = graph.cellEditor.isStopEditingEvent;
        graph.cellEditor.isStopEditingEvent = function (evt) {
            return cellEditorIsStopEditingEvent.apply(this, arguments) ||
                (evt.keyCode == 13 && ((!mxClient.IS_SF && mxEvent.isControlDown(evt)) ||
                    (mxClient.IS_MAC && mxEvent.isMetaDown(evt)) ||
                    (mxClient.IS_SF && mxEvent.isShiftDown(evt))));
        };

        // 添加空格+滚轮缩放功能
        var graphIsZoomWheelEvent = graph.isZoomWheelEvent;

        graph.isZoomWheelEvent = function () {
            return spaceKeyPressed || graphIsZoomWheelEvent.apply(this, arguments);
        };

        // 为文本编辑切换工具栏
        var textMode = false;
        var fontMenu = null;
        var sizeMenu = null;
        var nodes = null;

        var updateToolbar = mxUtils.bind(this, function () {
            if (this.toolbar != null && textMode != graph.cellEditor.isContentEditing()) {
                var node = this.toolbar.container.firstChild;
                var newNodes = [];

                while (node != null) {
                    var tmp = node.nextSibling;

                    if (mxUtils.indexOf(this.toolbar.staticElements, node) < 0) {
                        node.parentNode.removeChild(node);
                        newNodes.push(node);
                    }

                    node = tmp;
                }

                // 保存对特殊项目的引用
                var tmp1 = this.toolbar.fontMenu;
                var tmp2 = this.toolbar.sizeMenu;

                if (nodes == null) {
                    this.toolbar.createTextToolbar();
                } else {
                    for (var i = 0; i < nodes.length; i++) {
                        this.toolbar.container.appendChild(nodes[i]);
                    }

                    // 恢复对特殊项目的引用
                    this.toolbar.fontMenu = fontMenu;
                    this.toolbar.sizeMenu = sizeMenu;
                }

                textMode = graph.cellEditor.isContentEditing();
                fontMenu = tmp1;
                sizeMenu = tmp2;
                nodes = newNodes;
            }
        });

        var ui = this;

        // 覆盖单元格编辑器以更新工具栏
        var cellEditorStartEditing = graph.cellEditor.startEditing;
        graph.cellEditor.startEditing = function () {
            cellEditorStartEditing.apply(this, arguments);
            updateToolbar();

            if (graph.cellEditor.isContentEditing()) {
                var updating = false;

                var updateCssHandler = function () {
                    if (!updating) {
                        updating = true;

                        window.setTimeout(function () {
                            var node = graph.getSelectedEditingElement();

                            if (node != null) {
                                var css = mxUtils.getCurrentStyle(node);

                                if (css != null && ui.toolbar != null) {
                                    ui.toolbar.setFontName(Graph.stripQuotes(css.fontFamily));
                                    ui.toolbar.setFontSize(parseInt(css.fontSize));
                                }
                            }

                            updating = false;
                        }, 0);
                    }
                };

                mxEvent.addListener(graph.cellEditor.textarea, 'input', updateCssHandler)
                mxEvent.addListener(graph.cellEditor.textarea, 'touchend', updateCssHandler);
                mxEvent.addListener(graph.cellEditor.textarea, 'mouseup', updateCssHandler);
                mxEvent.addListener(graph.cellEditor.textarea, 'keyup', updateCssHandler);
                updateCssHandler();
            }
        };

        // 更新工具栏并处理可能的错误
        var cellEditorStopEditing = graph.cellEditor.stopEditing;
        graph.cellEditor.stopEditing = function (cell, trigger) {
            try {
                cellEditorStopEditing.apply(this, arguments);
                updateToolbar();
            } catch (e) {
                ui.handleError(e);
            }
        };

        // 启用滚动条并为容器设置光标样式
        graph.container.setAttribute('tabindex', '0');
        graph.container.style.cursor = 'default';

        // 通过iframe嵌入时的页面滚动解决方案
        if (window.self === window.top && graph.container.parentNode != null) {
            try {
                graph.container.focus();
            } catch (e) {
                // 忽略旧版本IE中的错误
            }
        }

        // 鼠标按下时保持图形容器聚焦
        var graphFireMouseEvent = graph.fireMouseEvent;
        graph.fireMouseEvent = function (evtName, me, sender) {
            if (evtName == mxEvent.MOUSE_DOWN) {
                console.log('focus...');
                this.container.focus();

                // drawioBus.$emit('cellFocus')

                // 组件实例的右侧工具栏
                mianCallBack(window.myEditor)
            }

            graphFireMouseEvent.apply(this, arguments);
        };

        // 配置鼠标悬停时的自动展开
        graph.popupMenuHandler.autoExpand = true;

        // 安装上下文菜单
        if (this.menus != null) {
            graph.popupMenuHandler.factoryMethod = mxUtils.bind(this, function (menu, cell, evt) {
                this.menus.createPopupMenu(menu, cell, evt);
            });
        }

        // 隐藏上下文菜单
        mxEvent.addGestureListeners(document, mxUtils.bind(this, function (evt) {
            graph.popupMenuHandler.hideMenu();
        }));

        // 创建按键事件的处理程序
        this.keyHandler = this.createKeyHandler(editor);

        // 按键处理程序的获取器
        this.getKeyHandler = function () {
            return keyHandler;
        };

        // 存储当前样式并将其分配给新单元格
        var styles = ['rounded', 'shadow', 'glass', 'dashed', 'dashPattern', 'labelBackgroundColor',
            'comic', 'sketch', 'fillWeight', 'hachureGap', 'hachureAngle', 'jiggle',
            'disableMultiStroke', 'disableMultiStrokeFill', 'fillStyle', 'curveFitting',
            'simplification', 'sketchStyle'
        ];
        var connectStyles = ['shape', 'edgeStyle', 'curved', 'rounded', 'elbow', 'jumpStyle', 'jumpSize',
            'comic', 'sketch', 'fillWeight', 'hachureGap', 'hachureAngle', 'jiggle',
            'disableMultiStroke', 'disableMultiStrokeFill', 'fillStyle', 'curveFitting',
            'simplification', 'sketchStyle'
        ];

        // 注意：不在样式中的所有内容都会被忽略（样式会在下面进行扩展）
        this.setAsDefaultStyle = function (cell) {
            /**
             * 存储一份metaId-style的数据，后续添加元素根据
             */
            graph.addDefaultStyle(cell)
            return
            try {
                var state = graph.view.getState(cell);

                if (state != null) {
                    // 忽略默认样式
                    var clone = cell.clone();
                    clone.style = ''
                    var defaultStyle = graph.getCellStyle(clone);
                    var values = [];
                    var keys = [];

                    for (var key in state.style) {
                        if (defaultStyle[key] != state.style[key]) {
                            values.push(state.style[key]);
                            keys.push(key);
                        }
                    }

                    // 处理值为"none"的特殊情况
                    var cellStyle = graph.getModel().getStyle(state.cell);
                    var tokens = (cellStyle != null) ? cellStyle.split(';') : [];

                    for (var i = 0; i < tokens.length; i++) {
                        var tmp = tokens[i];
                        var pos = tmp.indexOf('=');

                        if (pos >= 0) {
                            var key = tmp.substring(0, pos);
                            var value = tmp.substring(pos + 1);

                            if (defaultStyle[key] != null && value == 'none') {
                                values.push(value);
                                keys.push(key);
                            }
                        }
                    }

                    // 重置当前样式
                    if (graph.getModel().isEdge(state.cell)) {
                        graph.currentEdgeStyle = {};
                    } else {
                        graph.currentVertexStyle = {}
                    }

                    this.fireEvent(new mxEventObject('styleChanged', 'keys', keys, 'values', values, 'cells', [state.cell]));
                }
            } catch (e) {
                this.handleError(e);
            }
        };

        this.clearDefaultStyle = function () {
            graph.currentEdgeStyle = mxUtils.clone(graph.defaultEdgeStyle);
            graph.currentVertexStyle = mxUtils.clone(graph.defaultVertexStyle);

            // 更新UI
            this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
        };

        // 如果单元格有值则应该忽略的键（已知：所有新单元格的默认值是html=1，所以
        // 对于html键，这实际上只对通过连接处理程序插入的边有效）
        var valueStyles = ['fontFamily', 'fontSource', 'fontSize', 'fontColor'];

        // 无论选择如何都会更新当前边样式的键
        var alwaysEdgeStyles = ['edgeStyle', 'startArrow', 'startFill', 'startSize', 'endArrow',
            'endFill', 'endSize'
        ];

        // 一起被忽略的键（如果一个出现，所有都被忽略）
        var keyGroups = [
            ['startArrow', 'startFill', 'startSize', 'sourcePerimeterSpacing',
                'endArrow', 'endFill', 'endSize', 'targetPerimeterSpacing'
            ],
            ['strokeColor', 'strokeWidth'],
            ['fillColor', 'gradientColor'],
            valueStyles,
            ['opacity'],
            ['align'],
            ['html']
        ];

        // 将上面使用的所有键添加到样式数组中
        for (var i = 0; i < keyGroups.length; i++) {
            for (var j = 0; j < keyGroups[i].length; j++) {
                styles.push(keyGroups[i][j]);
            }
        }

        for (var i = 0; i < connectStyles.length; i++) {
            if (mxUtils.indexOf(styles, connectStyles[i]) < 0) {
                styles.push(connectStyles[i]);
            }
        }

        // 为边和顶点实现全局当前样式，该样式会应用到新单元格
        var insertHandler = function (cells, asText, model) {
            model = (model != null) ? model : graph.getModel();

            model.beginUpdate();
            try {
                for (var i = 0; i < cells.length; i++) {
                    var cell = cells[i];

                    var appliedStyles;

                    if (asText) {
                        // 只应用基本文本样式
                        appliedStyles = ['fontSize', 'fontFamily', 'fontColor'];
                    } else {
                        // 从要应用的样式中移除单元格样式中已定义的样式
                        var cellStyle = model.getStyle(cell);
                        var tokens = (cellStyle != null) ? cellStyle.split(';') : [];
                        appliedStyles = styles.slice();

                        for (var j = 0; j < tokens.length; j++) {
                            var tmp = tokens[j];
                            var pos = tmp.indexOf('=');

                            if (pos >= 0) {
                                var key = tmp.substring(0, pos);
                                var index = mxUtils.indexOf(appliedStyles, key);

                                if (index >= 0) {
                                    appliedStyles.splice(index, 1);
                                }

                                // 处理一个已定义样式忽略其他样式的特殊情况
                                for (var k = 0; k < keyGroups.length; k++) {
                                    var group = keyGroups[k];

                                    if (mxUtils.indexOf(group, key) >= 0) {
                                        for (var l = 0; l < group.length; l++) {
                                            var index2 = mxUtils.indexOf(appliedStyles, group[l]);

                                            if (index2 >= 0) {
                                                appliedStyles.splice(index2, 1);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // 将当前样式应用到单元格
                    var edge = model.isEdge(cell);
                    var current = (edge) ? graph.currentEdgeStyle : graph.currentVertexStyle;
                    var newStyle = model.getStyle(cell);

                    for (var j = 0; j < appliedStyles.length; j++) {
                        var key = appliedStyles[j];
                        var styleValue = current[key];

                        if (styleValue != null && (key != 'shape' || edge)) {
                            // 特殊情况：连接样式不在这里应用，而是在连接处理程序中应用
                            if (!edge || mxUtils.indexOf(connectStyles, key) < 0) {
                                newStyle = mxUtils.setStyle(newStyle, key, styleValue);
                            }
                        }
                    }

                    model.setStyle(cell, newStyle);
                }
            } finally {
                model.endUpdate();
            }
        };

        graph.addListener('cellsInserted', function (sender, evt) {
            insertHandler(evt.getProperty('cells'));
        });

        graph.addListener('textInserted', function (sender, evt) {
            insertHandler(evt.getProperty('cells'), true);
        });

        this.insertHandler = insertHandler;

        graph.connectionHandler.addListener(mxEvent.CONNECT, function (sender, evt) {
            var cells = [evt.getProperty('cell')];

            if (evt.getProperty('terminalInserted')) {
                cells.push(evt.getProperty('terminal'));
            }

            insertHandler(cells);
        });

        this.addListener('styleChanged', mxUtils.bind(this, function (sender, evt) {
            // 检查边和/或顶点是否被修改
            var cells = evt.getProperty('cells');
            var vertex = false;
            var edge = false;

            if (cells.length > 0) {
                for (var i = 0; i < cells.length; i++) {
                    vertex = graph.getModel().isVertex(cells[i]) || vertex;
                    edge = graph.getModel().isEdge(cells[i]) || edge;

                    if (edge && vertex) {
                        break;
                    }
                }
            } else {
                vertex = true;
                edge = true;
            }

            var keys = evt.getProperty('keys');
            var values = evt.getProperty('values');

            for (var i = 0; i < keys.length; i++) {
                var common = mxUtils.indexOf(valueStyles, keys[i]) >= 0;

                // 忽略透明的描边颜色
                if (keys[i] != 'strokeColor' || (values[i] != null && values[i] != 'none')) {
                    // 特殊情况：边样式和形状
                    if (mxUtils.indexOf(connectStyles, keys[i]) >= 0) {
                        if (edge || mxUtils.indexOf(alwaysEdgeStyles, keys[i]) >= 0) {
                            if (values[i] == null) {
                                delete graph.currentEdgeStyle[keys[i]];
                            } else {
                                // graph.currentEdgeStyle[keys[i]] = values[i];
                            }
                        }
                        // 如果在样式中定义了，则使用顶点样式
                        else if (vertex && mxUtils.indexOf(styles, keys[i]) >= 0) {
                            if (values[i] == null) {
                                delete graph.currentVertexStyle[keys[i]];
                            } else {
                                graph.currentVertexStyle[keys[i]] = values[i];
                            }
                        }
                    } else if (mxUtils.indexOf(styles, keys[i]) >= 0) {
                        if (vertex || common) {
                            if (values[i] == null) {
                                delete graph.currentVertexStyle[keys[i]];
                            } else {
                                graph.currentVertexStyle[keys[i]] = values[i];
                            }
                        }

                        if (edge || common || mxUtils.indexOf(alwaysEdgeStyles, keys[i]) >= 0) {
                            if (values[i] == null) {
                                delete graph.currentEdgeStyle[keys[i]];
                            } else {
                                // graph.currentEdgeStyle[keys[i]] = values[i];
                            }
                        }
                    }
                }
            }

            if (this.toolbar != null) {
                this.toolbar.setFontName(graph.currentVertexStyle['fontFamily'] || Menus.prototype.defaultFont);
                this.toolbar.setFontSize(graph.currentVertexStyle['fontSize'] || Menus.prototype.defaultFontSize);
                /**
                  if (this.toolbar.edgeStyleMenu != null) {
                      // 更新边样式的工具栏图标
                      var edgeStyleDiv = this.toolbar.edgeStyleMenu.getElementsByTagName('div')[0];

                      if (graph.currentEdgeStyle['edgeStyle'] == 'orthogonalEdgeStyle' && graph.currentEdgeStyle['curved'] == '1') {
                          edgeStyleDiv.className = 'geSprite geSprite-curved';
                      } else if (graph.currentEdgeStyle['edgeStyle'] == 'straight' || graph.currentEdgeStyle['edgeStyle'] == 'none' ||
                          graph.currentEdgeStyle['edgeStyle'] == null) {
                          edgeStyleDiv.className = 'geSprite geSprite-straight';
                      } else if (graph.currentEdgeStyle['edgeStyle'] == 'entityRelationEdgeStyle') {
                          edgeStyleDiv.className = 'geSprite geSprite-entity';
                      } else if (graph.currentEdgeStyle['edgeStyle'] == 'elbowEdgeStyle') {
                          edgeStyleDiv.className = 'geSprite geSprite-' + ((graph.currentEdgeStyle['elbow'] == 'vertical') ?
                              'verticalelbow' : 'horizontalelbow');
                      } else if (graph.currentEdgeStyle['edgeStyle'] == 'isometricEdgeStyle') {
                          edgeStyleDiv.className = 'geSprite geSprite-' + ((graph.currentEdgeStyle['elbow'] == 'vertical') ?
                              'verticalisometric' : 'horizontalisometric');
                      } else {
                          edgeStyleDiv.className = 'geSprite geSprite-orthogonal';
                      }
                  }

                  if (this.toolbar.edgeShapeMenu != null) {
                      // 更新边形状的图标
                      var edgeShapeDiv = this.toolbar.edgeShapeMenu.getElementsByTagName('div')[0];

                      if (graph.currentEdgeStyle['shape'] == 'link') {
                          edgeShapeDiv.className = 'geSprite geSprite-linkedge';
                      } else if (graph.currentEdgeStyle['shape'] == 'flexArrow') {
                          edgeShapeDiv.className = 'geSprite geSprite-arrow';
                      } else if (graph.currentEdgeStyle['shape'] == 'arrow') {
                          edgeShapeDiv.className = 'geSprite geSprite-simplearrow';
                      } else {
                          edgeShapeDiv.className = 'geSprite geSprite-connection';
                      }
                  }
                   */
                // 更新可选线条起始形状的图标
                if (this.toolbar.lineStartMenu != null) {
                    var lineStartDiv = this.toolbar.lineStartMenu.getElementsByTagName('div')[0];

                    lineStartDiv.className = this.getCssClassForMarker('start',
                        graph.currentEdgeStyle['shape'], graph.currentEdgeStyle[mxConstants.STYLE_STARTARROW],
                        mxUtils.getValue(graph.currentEdgeStyle, 'startFill', '1'));
                }

                // 更新可选线条结束形状的图标
                if (this.toolbar.lineEndMenu != null) {
                    var lineEndDiv = this.toolbar.lineEndMenu.getElementsByTagName('div')[0];

                    lineEndDiv.className = this.getCssClassForMarker('end',
                        graph.currentEdgeStyle['shape'], graph.currentEdgeStyle[mxConstants.STYLE_ENDARROW],
                        mxUtils.getValue(graph.currentEdgeStyle, 'endFill', '1'));
                }
            }
        }));

        // 更新字体大小和字体系列标签
        if (this.toolbar != null) {
            var update = mxUtils.bind(this, function () {
                var ff = graph.currentVertexStyle['fontFamily'] || 'Helvetica';
                var fs = String(graph.currentVertexStyle['fontSize'] || '12');
                var state = graph.getView().getState(graph.getSelectionCell());

                if (state != null) {
                    ff = state.style[mxConstants.STYLE_FONTFAMILY] || ff;
                    fs = state.style[mxConstants.STYLE_FONTSIZE] || fs;

                    if (ff.length > 10) {
                        ff = ff.substring(0, 8) + '...';
                    }
                }
                if (this.toolbar) {
                    this.toolbar.setFontName(ff);
                    this.toolbar.setFontSize(fs);
                }
            });

            graph.getSelectionModel().addListener(mxEvent.CHANGE, update);
            graph.getModel().addListener(mxEvent.CHANGE, update);
        }

        // 确保添加单元格时当前图层可见
        graph.addListener(mxEvent.CELLS_ADDED, function (sender, evt) {
            var cells = evt.getProperty('cells');
            var parent = evt.getProperty('parent');

            if (graph.getModel().isLayer(parent) && !graph.isCellVisible(parent) && cells != null && cells.length > 0) {
                graph.getModel().setVisible(parent, true);
            }
        });

        // 全局处理程序，用于隐藏当前菜单
        this.gestureHandler = mxUtils.bind(this, function (evt) {
            if (this.currentMenu != null && mxEvent.getSource(evt) != this.currentMenu.div) {
                this.hideCurrentMenu();
            }
        });

        mxEvent.addGestureListeners(document, this.gestureHandler);

        // 在窗口大小调整或方向改变后更新编辑器UI
        // 超时是针对旧版本IE的解决方案，这些版本在DOM客户端大小时有延迟。
        // 不应该使用大于0的延迟，以避免在窗口调整大小时处理多次重绘
        this.resizeHandler = mxUtils.bind(this, function () {
            window.setTimeout(mxUtils.bind(this, function () {
                if (this.editor.graph != null) {
                    this.refresh();
                }
            }), 0);
        });

        mxEvent.addListener(window, 'resize', this.resizeHandler);

        this.orientationChangeHandler = mxUtils.bind(this, function () {
            this.refresh();
        });

        mxEvent.addListener(window, 'orientationchange', this.orientationChangeHandler);

        // iOS上bug的解决方案，见
        // http://stackoverflow.com/questions/19012135/ios-7-ipad-safari-landscape-innerheight-outerheight-layout-issue
        if (mxClient.IS_IOS && !window.navigator.standalone) {
            this.scrollHandler = mxUtils.bind(this, function () {
                window.scrollTo(0, 0);
            });

            mxEvent.addListener(window, 'scroll', this.scrollHandler);
        }

        /**
         * 文件加载后设置初始滚动条位置。
         */
        this.editor.addListener('resetGraphView', mxUtils.bind(this, function () {
            this.resetScrollbars();
        }));

        /**
         * 当网格启用状态改变时重绘背景。
         */
        this.addListener('gridEnabledChanged', mxUtils.bind(this, function () {
            graph.view.validateBackground();
        }));

        this.addListener('backgroundColorChanged', mxUtils.bind(this, function () {
            graph.view.validateBackground();
        }));

        /**
         * 当网格大小改变时重绘网格。
         */
        graph.addListener('gridSizeChanged', mxUtils.bind(this, function () {
            if (graph.isGridEnabled()) {
                graph.view.validateBackground();
            }
        }));

        // 重置UI，更新动作和菜单状态
        this.editor.resetGraph();
    }

    this.init();

    if (!graph.standalone) {
        this.open();
    }

    const stylesheet = new mxStylesheet();
    const defaultStyle = stylesheet.getDefaultVertexStyle();
    // 只能垂直移动
    defaultStyle.verticalOnly = 0;
    // 只能水平移动
    defaultStyle.horizontalOnly = 0;
    graph.overHandler && graph.overHandler.destroy()
    graph.overHandler = new mxOverHandler(this)
};

// 扩展 mxEventSource
mxUtils.extend(EditorUi, mxEventSource);

/**
 * 全局配置，指定是否使用紧凑UI元素。
 */
/**
 * 是否启用紧凑UI模式。
 * 在紧凑模式下，UI元素会更加紧凑以节省空间。
 */
EditorUi.compactUi = true;

/**
 * 分割条的大小。根据设备类型自动调整，触摸设备为12像素，其他设备为8像素。
 */
EditorUi.prototype.splitSize = (mxClient.IS_TOUCH || mxClient.IS_POINTER) ? 12 : 8;

/**
 * 菜单栏的高度。默认为0（可能被禁用）。
 */
EditorUi.prototype.menubarHeight = 0;

/**
 * 是否启用格式面板。默认为true。
 */
EditorUi.prototype.formatEnabled = true;

/**
 * 格式面板的宽度。默认为240像素。
 */
EditorUi.prototype.formatWidth = 240;

/**
 * 工具栏的高度。默认为38像素。
 */
EditorUi.prototype.toolbarHeight = 38;

/**
 * 页脚的高度。默认为28像素。
 */
EditorUi.prototype.footerHeight = 28;

/**
 * 可选的侧边栏页脚容器高度。默认为34像素。
 * 更多图形高度
 */
EditorUi.prototype.sidebarFooterHeight = 0;

/**
 * 水平分割条的位置。根据屏幕宽度和侧边栏条目设置自动调整。
 * 小屏幕(≤640px)为218px，普通侧边栏为200px，大型侧边栏为250px。
 */
EditorUi.prototype.hsplitPosition = (screen.width <= 640) ? 218 : ((urlParams['sidebar-entries'] != 'large') ? 200 : 250);

/**
 * 指定是否允许在 <executeLayout> 中使用动画。默认为true。
 */
EditorUi.prototype.allowAnimation = true;

/**
 * 灯箱模式最大适应缩放比例。默认为2。
 */
EditorUi.prototype.lightboxMaxFitScale = 2;

/**
 * 灯箱模式垂直分割器。默认为4。
 */
EditorUi.prototype.lightboxVerticalDivider = 4;

/**
 * 指定单击水平分割条是否应该折叠侧边栏。默认为false。
 */
EditorUi.prototype.hsplitClickEnabled = false;

/**
 * 初始化图形编辑器UI的主要组件和事件监听器。
 * 设置形状选择器、滚动处理、键盘事件等基本功能。
 */
EditorUi.prototype.init = function () {
    var graph = this.editor.graph;

    if (!graph.standalone) {
        if (urlParams['shape-picker'] != '0') {
            this.installShapePicker();
        }

        // 滚动时隐藏工具提示和连接点
        mxEvent.addListener(graph.container, 'scroll', mxUtils.bind(this, function () {
            graph.tooltipHandler.hide();

            if (graph.connectionHandler != null && graph.connectionHandler.constraintHandler != null) {
                graph.connectionHandler.constraintHandler.reset();
            }
        }));

        // 按ESC键时隐藏工具提示
        graph.addListener(mxEvent.ESCAPE, mxUtils.bind(this, function () {
            graph.tooltipHandler.hide();
            var rb = graph.getRubberband();

            if (rb != null) {
                rb.cancel();
            }
            // esc快捷键退出戳记模式
            window.isPokePatttern = false
            window.myEditor.graphEvent.exitAddPattern()
            graph.isMouseDown = false
            this.sidebar.updateToolStatus()
        }));

        mxEvent.addListener(graph.container, 'keydown', mxUtils.bind(this, function (evt) {
            this.onKeyDown(evt);
        }));

        mxEvent.addListener(graph.container, 'keypress', mxUtils.bind(this, function (evt) {
            this.onKeyPress(evt);
        }));

        // 更新动作状态
        this.addUndoListener();
        this.addBeforeUnloadListener();

        graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function () {
            this.updateActionStates();
        }));

        graph.getModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function () {
            this.updateActionStates();
        }));

        // 在默认父节点改变后更改动作状态
        var graphSetDefaultParent = graph.setDefaultParent;
        var ui = this;

        this.editor.graph.setDefaultParent = function () {
            graphSetDefaultParent.apply(this, arguments);
            ui.updateActionStates();
        };

        // 黑客方法，使editLink在顶点处理程序中可用
        graph.editLink = ui.actions.get('editLink').funct;

        this.updateActionStates();
        this.initClipboard();
        this.initCanvas();

        if (this.format != null) {
            this.format.init();
        }
    }
};

/**
 * 检查给定事件是否应该开始编辑。
 * 这个实现总是返回true，表示允许编辑操作。
 */
/**
 * 安装形状选择器功能，为图形编辑器添加形状选择交互。
 * 设置鼠标事件监听器来处理形状选择器的显示和隐藏。
 */
EditorUi.prototype.installShapePicker = function () {
    var graph = this.editor.graph;
    var ui = this;

    // 使用此事件处理鼠标按下事件，在选择状态改变前检查选择状态
    graph.addListener(mxEvent.FIRE_MOUSE_EVENT, mxUtils.bind(this, function (sender, evt) {
        if (evt.getProperty('eventName') == 'mouseDown') {
            ui.hideShapePicker();
        }
    }));

    graph.addListener(mxEvent.ESCAPE, mxUtils.bind(this, function () {
        ui.hideShapePicker(true);
    }));

    graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function () {
        ui.hideShapePicker(true);
    }));

    graph.getModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function () {
        ui.hideShapePicker(true);
    }));

    // 算作弹出菜单
    var popupMenuHandlerIsMenuShowing = graph.popupMenuHandler.isMenuShowing;

    graph.popupMenuHandler.isMenuShowing = function () {
        return popupMenuHandlerIsMenuShowing.apply(this, arguments) || ui.shapePicker != null;
    };

    // 添加双击对话框用于插入形状
    var graphDblClick = graph.dblClick;

    graph.dblClick = function (evt, cell) {
        // 思维导图特殊处理
        if (window.zTreeObj ? .currentSelectedNode ? .type === 'mind_map') {
            if (cell.curDragNodes) {
                const {
                    type,
                    originId,
                    name
                } = cell.curDragNodes;
                // 跳转模型
                const modelType = sidebarStructure.draggableNodeTypes.filter(i => i !== 'file') // 去除file
                if (modelType.includes(type)) {
                    if (!originId) {
                        window.parent.$Message.error('无源模型！');
                    } else {
                        drawioBus.$emit('nodeClick', originId);
                    }
                }
                // 下载文件
                else if (type === 'file') {
                    window.parent
                        .$axios({
                            method: 'GET',
                            url: window.parent.g.ApiUrl2 + '/sysmlDefineNode/exportOthersSysmlNode?nodeId=' + originId,
                            responseType: 'arraybuffer',
                        })
                        .then(res => {
                            if (Object.prototype.toString.call(res) === '[object ArrayBuffer]') {
                                const a = document.createElement('a');
                                a.style.display = 'none';
                                a.href = window.URL.createObjectURL(new Blob([res]));
                                a.setAttribute('download', name);
                                document.body.appendChild(a);
                                a.click();
                                document.body.removeChild(a);
                            }
                        });
                } else {
                    return;
                }
            } else {
                let cell1 = this.insertTextForEvent(evt, cell);
                graphDblClick.call(this, evt, cell1);
                return;
            }
        }
        if (this.isEnabled()) {
            if (cell == null && ui.sidebar != null && !mxEvent.isShiftDown(evt)) {
                return;
                mxEvent.consume(evt);
                var pt = mxUtils.convertPoint(this.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));

                // 异步以避免双击后的直接插入
                window.setTimeout(mxUtils.bind(this, function () {
                    ui.showShapePicker(pt.x, pt.y);
                }), 30);
            } else {
                graphDblClick.apply(this, arguments);
            }
        }
    };

    if (this.hoverIcons != null) {
        var hoverIconsDrag = this.hoverIcons.drag;

        this.hoverIcons.drag = function () {
            ui.hideShapePicker();
            hoverIconsDrag.apply(this, arguments);
        };

        var hoverIconsExecute = this.hoverIcons.execute;

        this.hoverIcons.execute = function (state, dir, me) {
            var evt = me.getEvent();

            if (!this.graph.isCloneEvent(evt) && !mxEvent.isShiftDown(evt)) {
                this.graph.connectVertex(state.cell, dir, this.graph.defaultEdgeLength, evt, null, null, mxUtils.bind(this, function (x, y, execute) {
                    var temp = graph.getCompositeParent(state.cell);
                    var geo = graph.getCellGeometry(temp);
                    me.consume();

                    while (temp != null && graph.model.isVertex(temp) && geo != null && geo.relative) {
                        cell = temp;
                        temp = graph.model.getParent(cell)
                        geo = graph.getCellGeometry(temp);
                    }

                    // 异步以避免双击后的直接插入
                    window.setTimeout(mxUtils.bind(this, function () {
                        ui.showShapePicker(me.getGraphX(), me.getGraphY(), temp, mxUtils.bind(this, function (cell) {
                            execute(cell);
                        }), dir);
                    }), 30);
                }), mxUtils.bind(this, function (result) {
                    this.graph.selectCellsForConnectVertex(result, evt, this);
                }));
            } else {
                hoverIconsExecute.apply(this, arguments);
            }
        };
    }
};

/**
 * 在指定位置显示形状选择器。
 * 根据源元素显示相关的形状选项供用户选择。
 *
 * @param {number} x - 选择器的X坐标位置
 * @param {number} y - 选择器的Y坐标位置
 * @param {mxCell} source - 源元素，用于确定要显示的形状类型
 * @param {Function} callback - 选择形状后的回调函数
 * @param {string} direction - 显示方向
 */
EditorUi.prototype.showShapePicker = function (x, y, source, callback, direction) {
    var cells = this.getCellsForShapePicker(source);

    if (cells != null && cells.length > 0) {
        var ui = this;
        var graph = this.editor.graph;
        var div = document.createElement('div');
        var sourceState = graph.view.getState(source);
        var style = (source != null && (sourceState == null ||
                !graph.isTransparentState(sourceState))) ?
            graph.copyStyle(source) : null;

        // 对于触摸设备，不要将条目放在指针下方
        div.className = 'geToolbarContainer geSidebarContainer geSidebar';
        div.style.cssText = 'position:absolute;left:' + x + 'px;top:' + y +
            'px;width:140px;border-radius:9px;padding:4px;text-align:center;' +
            'box-shadow:0px 0px 3px 1px #d1d1d1;padding: 6px 0 8px 0;';
        mxUtils.setPrefixedStyle(div.style, 'transform', 'translate(-22px,-22px)');

        if (graph.background != null && graph.background != mxConstants.NONE) {
            div.style.backgroundColor = graph.background;
        }

        graph.container.appendChild(div);

        var addCell = mxUtils.bind(this, function (cell) {
            // 需要包装器来捕获事件
            var node = document.createElement('a');
            node.className = 'geItem';
            node.style.cssText = 'position:relative;display:inline-block;position:relative;' +
                'width:30px;height:30px;cursor:pointer;overflow:hidden;padding:3px 0 0 3px;';
            div.appendChild(node);

            if (style != null) {
                this.sidebar.graph.pasteStyle(style, [cell]);
            } else {
                ui.insertHandler([cell], cell.value != '', this.sidebar.graph.model);
            }

            this.sidebar.createThumb([cell], 25, 25, node, null, true, false, cell.geometry.width, cell.geometry.height);

            mxEvent.addListener(node, 'click', function () {
                var clone = graph.cloneCell(cell);

                if (callback != null) {
                    callback(clone);
                } else {
                    clone.geometry.x = graph.snap(Math.round(x / graph.view.scale) -
                        graph.view.translate.x - cell.geometry.width / 2);
                    clone.geometry.y = graph.snap(Math.round(y / graph.view.scale) -
                        graph.view.translate.y - cell.geometry.height / 2);

                    graph.model.beginUpdate();
                    try {
                        graph.addCell(clone);
                    } finally {
                        graph.model.endUpdate();
                    }

                    graph.setSelectionCell(clone);
                    graph.scrollCellToVisible(clone);
                    graph.startEditingAtCell(clone);

                    if (ui.hoverIcons != null) {
                        ui.hoverIcons.update(graph.view.getState(clone));
                    }
                }

                ui.hideShapePicker();
            });
        });

        for (var i = 0; i < cells.length; i++) {
            addCell(cells[i]);
        }

        if (ui.hoverIcons != null) {
            ui.hoverIcons.reset();
        }

        graph.popupMenuHandler.hideMenu();
        graph.tooltipHandler.hideTooltip();
        this.hideCurrentMenu();
        this.hideShapePicker();

        this.shapePickerCallback = callback;
        this.shapePicker = div;
    }
};

/**
 * 获取形状选择器中要显示的图形元素列表。
 * 根据输入的单元格类型返回相应的形状选项。
 *
 * @param {mxCell} cell - 源单元格，用于确定要显示的形状类型
 * @returns {Array} 要显示在形状选择器中的图形元素数组
 */
EditorUi.prototype.getCellsForShapePicker = function (cell) {
    var createVertex = mxUtils.bind(this, function (style, w, h, value) {
        return this.editor.graph.createVertex(null, null, value || '', 0, 0, w || 120, h || 60, style, false);
    });

    return [(cell != null) ? this.editor.graph.cloneCell(cell) :
        createVertex('text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;', 40, 20, 'Text'),
        createVertex('whiteSpace=wrap;html=1;'),
        createVertex('ellipse;whiteSpace=wrap;html=1;', 120, 80),
        createVertex('rhombus;whiteSpace=wrap;html=1;', 80, 80),
        createVertex('shape=parallelogram;perimeter=parallelogramPerimeter;whiteSpace=wrap;html=1;fixedSize=1;'),
        createVertex('shape=trapezoid;perimeter=trapezoidPerimeter;whiteSpace=wrap;html=1;fixedSize=1;', 120, 60),
        createVertex('shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;', 120, 80),
        createVertex('shape=step;perimeter=stepPerimeter;whiteSpace=wrap;html=1;fixedSize=1;', 120, 80),
        createVertex('shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;'),
        createVertex('shape=cube;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;darkOpacity=0.05;darkOpacity2=0.1;', 120, 80),
        createVertex('shape=note;whiteSpace=wrap;html=1;backgroundOutline=1;darkOpacity=0.05;', 80, 100),
        createVertex('triangle;whiteSpace=wrap;html=1;', 60, 80),
        createVertex('shape=document;whiteSpace=wrap;html=1;boundedLbl=1;', 120, 80),
        createVertex('shape=tape;whiteSpace=wrap;html=1;', 120, 100),
        createVertex('ellipse;shape=cloud;whiteSpace=wrap;html=1;', 120, 80),
        createVertex('shape=cylinder;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;', 60, 80)
    ];
};

/**
 * 隐藏形状选择器并清理相关状态。
 * 如果未取消且有回调函数，则执行回调。
 *
 * @param {boolean} cancel - 是否取消选择操作
 */
EditorUi.prototype.hideShapePicker = function (cancel) {
    if (this.shapePicker != null) {
        this.shapePicker.parentNode.removeChild(this.shapePicker);
        this.shapePicker = null;

        if (!cancel && this.shapePickerCallback != null) {
            this.shapePickerCallback();
        }

        this.shapePickerCallback = null;
    }
};

/**
 * 键盘按下事件处理函数。
 * 处理各种键盘快捷键和编辑操作。
 *
 * @param {KeyboardEvent} evt - 键盘事件对象
 */
EditorUi.prototype.onKeyDown = function (evt) {
    var graph = this.editor.graph;

    // Tab键选择下一个单元格
    if (evt.which == 9 && graph.isEnabled() && !mxEvent.isAltDown(evt) &&
        (!graph.isEditing() || !mxEvent.isShiftDown(evt))) {
        if (graph.isEditing()) {
            graph.stopEditing(false);
        } else {
            graph.selectCell(!mxEvent.isShiftDown(evt));
        }

        mxEvent.consume(evt);
    }

    if (evt.code === 'Insert') {
        window.isPokePatttern = !window.isPokePatttern
        window.myEditor.graphEvent.exitAddPattern()
        this.sidebar.updateToolStatus()
    }
};

/**
 * 键盘按键事件处理函数。
 * 处理字符输入相关的键盘事件。
 *
 * @param {KeyboardEvent} evt - 键盘事件对象
 */
EditorUi.prototype.onKeyPress = function (evt) {
    var graph = this.editor.graph;

    // 已知：在怪异模式下，如果标签为空，焦点将无法工作
    if (this.isImmediateEditingEvent(evt) && !graph.isEditing() && !graph.isSelectionEmpty() && evt.which !== 0 &&
        evt.which !== 27 && !mxEvent.isAltDown(evt) && !mxEvent.isControlDown(evt) && !mxEvent.isMetaDown(evt)) {
        // 实体元素不能手动输入label
        const selection = graph.getSelectionCell()
        if (selection.value instanceof Object) return

        graph.escape();
        graph.startEditing();

        // Firefox中如果光标放在字符前字符会丢失的解决方案
        if (mxClient.IS_FF) {
            var ce = graph.cellEditor;

            if (ce.textarea != null) {
                ce.textarea.innerHTML = String.fromCharCode(evt.which);

                // 将光标移动到文本区域末尾
                var range = document.createRange();
                range.selectNodeContents(ce.textarea);
                range.collapse(false);
                var sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    }
};

/**
 * 检查给定的键盘事件是否应该立即开始编辑。
 * 这个实现总是返回true，表示任何键盘事件都可以触发编辑。
 */
/**
 * 检查是否应该立即开始编辑。
 * 确定给定的键盘事件是否应该触发单元格的立即编辑模式。
 *
 * @param {KeyboardEvent} evt - 键盘事件对象
 * @returns {boolean} 如果应该立即编辑则返回true
 */
EditorUi.prototype.isImmediateEditingEvent = function (evt) {
    return true;
};

/**
 * 获取标记的CSS类名。
 * 根据标记类型和样式返回相应的CSS类名。
 *
 * @param {string} prefix - CSS类名前缀
 * @param {string} shape - 形状类型
 * @param {string} marker - 标记类型
 * @param {string} fill - 填充类型
 * @returns {string} CSS类名
 */
EditorUi.prototype.getCssClassForMarker = function (prefix, shape, marker, fill) {
    var result = '';

    if (shape == 'flexArrow') {
        result = (marker != null && marker != mxConstants.NONE) ?
            'geSprite geSprite-' + prefix + 'blocktrans' : 'geSprite geSprite-noarrow';
    } else {
        // SVG标记精灵
        if (marker == 'box' || marker == 'halfCircle') {
            result = 'geSprite geSvgSprite geSprite-' + marker + ((prefix == 'end') ? ' geFlipSprite' : '');
        } else if (marker == mxConstants.ARROW_CLASSIC) {
            result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'classic' : 'geSprite geSprite-' + prefix + 'classictrans';
        } else if (marker == mxConstants.ARROW_CLASSIC_THIN) {
            result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'classicthin' : 'geSprite geSprite-' + prefix + 'classicthintrans';
        } else if (marker == mxConstants.ARROW_OPEN) {
            result = 'geSprite geSprite-' + prefix + 'open';
        } else if (marker == mxConstants.ARROW_OPEN_THIN) {
            result = 'geSprite geSprite-' + prefix + 'openthin';
        } else if (marker == mxConstants.ARROW_BLOCK) {
            result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'block' : 'geSprite geSprite-' + prefix + 'blocktrans';
        } else if (marker == mxConstants.ARROW_BLOCK_THIN) {
            result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'blockthin' : 'geSprite geSprite-' + prefix + 'blockthintrans';
        } else if (marker == mxConstants.ARROW_OVAL) {
            result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'oval' : 'geSprite geSprite-' + prefix + 'ovaltrans';
        } else if (marker == mxConstants.ARROW_DIAMOND) {
            result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'diamond' : 'geSprite geSprite-' + prefix + 'diamondtrans';
        } else if (marker == mxConstants.ARROW_DIAMOND_THIN) {
            result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'thindiamond' : 'geSprite geSprite-' + prefix + 'thindiamondtrans';
        } else if (marker == 'openAsync') {
            result = 'geSprite geSprite-' + prefix + 'openasync';
        } else if (marker == 'dash') {
            result = 'geSprite geSprite-' + prefix + 'dash';
        } else if (marker == 'cross') {
            result = 'geSprite geSprite-' + prefix + 'cross';
        } else if (marker == 'async') {
            result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'async' : 'geSprite geSprite-' + prefix + 'asynctrans';
        } else if (marker == 'circle' || marker == 'circlePlus') {
            result = (fill == '1' || marker == 'circle') ? 'geSprite geSprite-' + prefix + 'circle' : 'geSprite geSprite-' + prefix + 'circleplus';
        } else if (marker == 'ERone') {
            result = 'geSprite geSprite-' + prefix + 'erone';
        } else if (marker == 'ERmandOne') {
            result = 'geSprite geSprite-' + prefix + 'eronetoone';
        } else if (marker == 'ERmany') {
            result = 'geSprite geSprite-' + prefix + 'ermany';
        } else if (marker == 'ERoneToMany') {
            result = 'geSprite geSprite-' + prefix + 'eronetomany';
        } else if (marker == 'ERzeroToOne') {
            result = 'geSprite geSprite-' + prefix + 'eroneopt';
        } else if (marker == 'ERzeroToMany') {
            result = 'geSprite geSprite-' + prefix + 'ermanyopt';
        } else {
            result = 'geSprite geSprite-noarrow';
        }
    }

    return result;
};

/**
 * 在 Menus.js 中被重写。
 * 此方法的具体实现在菜单模块中定义。
 */
/**
 * 创建菜单系统。
 * 返回菜单管理器实例，用于处理应用程序的菜单功能。
 *
 * @returns {Object|null} 菜单管理器实例，默认为null
 */
EditorUi.prototype.createMenus = function () {
    return null;
};

/**
 * 更新粘贴操作的状态。
 * 根据剪贴板内容和当前选择状态更新粘贴相关的操作状态。
 */
EditorUi.prototype.updatePasteActionStates = function () {
    var graph;
    if (this.editor && this.editor.graph) {
        graph = this.editor.graph
    } else {
        graph = window.myEditor.editor.graph
    }
    var paste = this.actions.get('paste');
    var pasteHere = this.actions.get('pasteHere');

    paste.setEnabled(graph.cellEditor.isContentEditing() ||
        (((!mxClient.IS_FF && navigator.clipboard != null) || !mxClipboard.isEmpty()) &&
            graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent())));
    pasteHere.setEnabled(paste.isEnabled());
};

/**
 * 用于允许在特定事件中进行选择和上下文菜单的钩子函数。
 */
EditorUi.prototype.initClipboard = function () {
    var ui = this;

    var mxClipboardCut = mxClipboard.cut;
    mxClipboard.cut = function (graph) {
        if (graph.cellEditor.isContentEditing()) {
            document.execCommand('cut', false, null);
        } else {
            mxClipboardCut.apply(this, arguments);
        }

        ui.updatePasteActionStates();
    };

    var mxClipboardCopy = mxClipboard.copy;
    mxClipboard.copy = function (graph) {
        var result = null;

        if (graph.cellEditor.isContentEditing()) {
            document.execCommand('copy', false, null);
        } else {
            result = result || graph.getSelectionCells();
            result = graph.getExportableCells(graph.model.getTopmostCells(result));

            var cloneMap = new Object();
            var lookup = graph.createCellLookup(result);
            var clones = graph.cloneCells(result, null, cloneMap);

            // 使用临时模型强制分配新的ID
            // to avoid having to carry over the mapping from object
            // 从对象ID到单元格ID的映射到粘贴操作
            var model = new mxGraphModel();
            var parent = model.getChildAt(model.getRoot(), 0);

            for (var i = 0; i < clones.length; i++) {
                model.add(parent, clones[i]);

                // 检查孤立的相对子节点并使其成为绝对节点
                var state = graph.view.getState(result[i]);

                if (state != null) {
                    var geo = graph.getCellGeometry(clones[i]);

                    if (geo != null && geo.relative && !model.isEdge(result[i]) &&
                        lookup[mxObjectIdentity.get(model.getParent(result[i]))] == null) {
                        geo.offset = null;
                        geo.relative = false;
                        geo.x = state.x / state.view.scale - state.view.translate.x;
                        geo.y = state.y / state.view.scale - state.view.translate.y;
                    }
                }
            }

            graph.updateCustomLinks(graph.createCellMapping(cloneMap, lookup), clones);

            mxClipboard.insertCount = 1;
            mxClipboard.setCells(clones);
        }

        ui.updatePasteActionStates();

        return result;
    };

    var mxClipboardPaste = mxClipboard.paste;
    mxClipboard.paste = function (graph) {
        var result = null;

        if (graph.cellEditor.isContentEditing()) {
            document.execCommand('paste', false, null);
        } else {
            result = mxClipboardPaste.apply(this, arguments);
        }

        ui.updatePasteActionStates();

        return result;
    };

    // 覆盖单元格编辑器以更新粘贴动作状态
    var cellEditorStartEditing = this.editor.graph.cellEditor.startEditing;

    this.editor.graph.cellEditor.startEditing = function () {
        cellEditorStartEditing.apply(this, arguments);
        ui.updatePasteActionStates();
    };

    var cellEditorStopEditing = this.editor.graph.cellEditor.stopEditing;

    this.editor.graph.cellEditor.stopEditing = function (cell, trigger) {
        cellEditorStopEditing.apply(this, arguments);
        ui.updatePasteActionStates();
    };

    this.updatePasteActionStates();
};

/**
 * 延迟缩放延迟时间。
 * 使用CSS变换时的延迟缩放延迟（毫秒）。默认为20毫秒。
 */
EditorUi.prototype.lazyZoomDelay = 20;

/**
 * 滚轮缩放延迟时间。
 * 使用滚轮进行缩放时的延迟时间（毫秒）。默认为400毫秒。
 */
EditorUi.prototype.wheelZoomDelay = 400;

/**
 * 按钮缩放延迟时间。
 * 使用按钮进行缩放时的延迟时间（毫秒）。默认为600毫秒。
 */
EditorUi.prototype.buttonZoomDelay = 600;

/**
 * 初始化无限画布。
 */
EditorUi.prototype.initCanvas = function () {
    // 初始页面布局视图、滚动缓冲区和基于定时器的滚动
    var graph = this.editor.graph;
    graph.timerAutoScroll = true;

    /**
     * 返回页面视图中带有滚动条的页面填充。
     */
    graph.getPagePadding = function () {
        return new mxPoint(
            Math.max(0, Math.round((graph.container.offsetWidth - 34) / graph.view.scale)),
            Math.max(0, Math.round((graph.container.offsetHeight - 34) / graph.view.scale)),
        );
    };

    // 使背景页数量适应图形
    graph.view.getBackgroundPageBounds = function () {
        var layout = this.graph.getPageLayout();
        var page = this.graph.getPageSize();

        return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
            this.scale * (this.translate.y + layout.y * page.height),
            this.scale * layout.width * page.width,
            this.scale * layout.height * page.height);
    };

    graph.getPreferredPageSize = function (bounds, width, height) {
        var pages = this.getPageLayout();
        var size = this.getPageSize();

        return new mxRectangle(0, 0, pages.width * size.width, pages.height * size.height);
    };

    // 缩放页面/图形以适应可用大小
    var resize = null;
    var ui = this;

    if (this.editor.isChromelessView()) {
        resize = mxUtils.bind(this, function (autoscale, maxScale, cx, cy) {
            if (graph.container != null && !graph.isViewer()) {
                cx = (cx != null) ? cx : 0;
                cy = (cy != null) ? cy : 0;

                var bds = (graph.pageVisible) ? graph.view.getBackgroundPageBounds() : graph.getGraphBounds();
                var scroll = mxUtils.hasScrollbars(graph.container);
                var tr = graph.view.translate;
                var s = graph.view.scale;

                // 标准化边界
                var b = mxRectangle.fromRectangle(bds);
                b.x = b.x / s - tr.x;
                b.y = b.y / s - tr.y;
                b.width /= s;
                b.height /= s;

                var st = graph.container.scrollTop;
                var sl = graph.container.scrollLeft;
                var sb = (document.documentMode >= 8) ? 20 : 14;

                if (document.documentMode == 8 || document.documentMode == 9) {
                    sb += 3;
                }

                var cw = graph.container.offsetWidth - sb;
                var ch = graph.container.offsetHeight - sb;

                var ns = (autoscale) ? Math.max(0.3, Math.min(maxScale || 1, cw / b.width)) : s;
                var dx = ((cw - ns * b.width) / 2) / ns;
                var dy = (this.lightboxVerticalDivider == 0) ? 0 : ((ch - ns * b.height) / this.lightboxVerticalDivider) / ns;

                if (scroll) {
                    dx = Math.max(dx, 0);
                    dy = Math.max(dy, 0);
                }

                if (scroll || bds.width < cw || bds.height < ch) {
                    graph.view.scaleAndTranslate(ns, Math.floor(dx - b.x), Math.floor(dy - b.y));
                    graph.container.scrollTop = st * ns / s;
                    graph.container.scrollLeft = sl * ns / s;
                } else if (cx != 0 || cy != 0) {
                    var t = graph.view.translate;
                    graph.view.setTranslate(Math.floor(t.x + cx / s), Math.floor(t.y + cy / s));
                }
            }
        });

        // 黑客方法使函数可用于子类化者
        this.chromelessResize = resize;

        // 用于子类化者覆盖的钩子
        this.chromelessWindowResize = mxUtils.bind(this, function () {
            this.chromelessResize(false);
        });

        // 可移除的调整大小监听器
        var autoscaleResize = mxUtils.bind(this, function () {
            this.chromelessWindowResize(false);
        });

        mxEvent.addListener(window, 'resize', autoscaleResize);

        this.destroyFunctions.push(function () {
            mxEvent.removeListener(window, 'resize', autoscaleResize);
        });

        this.editor.addListener('resetGraphView', mxUtils.bind(this, function () {
            this.chromelessResize(true);
        }));

        this.actions.get('zoomIn').funct = mxUtils.bind(this, function (evt) {
            graph.zoomIn();
            this.chromelessResize(false);
        });
        this.actions.get('zoomOut').funct = mxUtils.bind(this, function (evt) {
            graph.zoomOut();
            this.chromelessResize(false);
        });

        // 为查看器创建工具栏 - 此处不要使用CSS
        // as this may be used in a viewer that has no CSS
        if (urlParams['toolbar'] != '0') {
            var toolbarConfig = JSON.parse(decodeURIComponent(urlParams['toolbar-config'] || '{}'));

            this.chromelessToolbar = document.createElement('div');
            this.chromelessToolbar.style.position = 'fixed';
            this.chromelessToolbar.style.overflow = 'hidden';
            this.chromelessToolbar.style.boxSizing = 'border-box';
            this.chromelessToolbar.style.whiteSpace = 'nowrap';
            this.chromelessToolbar.style.backgroundColor = '#000000';
            this.chromelessToolbar.style.padding = '10px 10px 8px 10px';
            this.chromelessToolbar.style.left = (graph.isViewer()) ? '0' : '50%';

            mxUtils.setPrefixedStyle(this.chromelessToolbar.style, 'borderRadius', '20px');
            mxUtils.setPrefixedStyle(this.chromelessToolbar.style, 'transition', 'opacity 600ms ease-in-out');

            var updateChromelessToolbarPosition = mxUtils.bind(this, function () {
                var css = mxUtils.getCurrentStyle(graph.container);

                if (graph.isViewer()) {
                    this.chromelessToolbar.style.top = '0';
                } else {
                    this.chromelessToolbar.style.bottom = ((css != null) ? parseInt(css['margin-bottom'] || 0) : 0) +
                        ((this.tabContainer != null) ? (20 + parseInt(this.tabContainer.style.height)) : 20) + 'px';
                }
            });

            this.editor.addListener('resetGraphView', updateChromelessToolbarPosition);
            updateChromelessToolbarPosition();

            var btnCount = 0;

            var addButton = mxUtils.bind(this, function (fn, imgSrc, tip) {
                btnCount++;

                var a = document.createElement('span');
                a.style.paddingLeft = '8px';
                a.style.paddingRight = '8px';
                a.style.cursor = 'pointer';
                mxEvent.addListener(a, 'click', fn);

                if (tip != null) {
                    a.setAttribute('title', tip);
                }

                var img = document.createElement('img');
                img.setAttribute('border', '0');
                img.setAttribute('src', imgSrc);

                a.appendChild(img);
                this.chromelessToolbar.appendChild(a);

                return a;
            });

            if (toolbarConfig.backBtn != null) {
                addButton(mxUtils.bind(this, function (evt) {
                    window.location.href = toolbarConfig.backBtn.url;
                    mxEvent.consume(evt);
                }), Editor.backLargeImage, mxResources.get('back', null, 'Back'));
            }

            if (this.isPagesEnabled()) {
                var prevButton = addButton(mxUtils.bind(this, function (evt) {
                    this.actions.get('previousPage').funct();
                    mxEvent.consume(evt);
                }), Editor.previousLargeImage, mxResources.get('previousPage'));

                var pageInfo = document.createElement('div');
                pageInfo.style.display = 'inline-block';
                pageInfo.style.verticalAlign = 'top';
                pageInfo.style.fontFamily = 'Helvetica,Arial';
                pageInfo.style.marginTop = '8px';
                pageInfo.style.fontSize = '14px';
                pageInfo.style.color = '#ffffff';
                this.chromelessToolbar.appendChild(pageInfo);

                var nextButton = addButton(mxUtils.bind(this, function (evt) {
                    this.actions.get('nextPage').funct();
                    mxEvent.consume(evt);
                }), Editor.nextLargeImage, mxResources.get('nextPage'));

                var updatePageInfo = mxUtils.bind(this, function () {
                    if (this.pages != null && this.pages.length > 1 && this.currentPage != null) {
                        pageInfo.innerHTML = '';
                        mxUtils.write(pageInfo, (mxUtils.indexOf(this.pages, this.currentPage) + 1) + ' / ' + this.pages.length);
                    }
                });

                prevButton.style.paddingLeft = '0px';
                prevButton.style.paddingRight = '4px';
                nextButton.style.paddingLeft = '4px';
                nextButton.style.paddingRight = '0px';

                var updatePageButtons = mxUtils.bind(this, function () {
                    if (this.pages != null && this.pages.length > 1 && this.currentPage != null) {
                        nextButton.style.display = '';
                        prevButton.style.display = '';
                        pageInfo.style.display = 'inline-block';
                    } else {
                        nextButton.style.display = 'none';
                        prevButton.style.display = 'none';
                        pageInfo.style.display = 'none';
                    }

                    updatePageInfo();
                });

                this.editor.addListener('resetGraphView', updatePageButtons);
                this.editor.addListener('pageSelected', updatePageInfo);
            }

            addButton(mxUtils.bind(this, function (evt) {
                this.actions.get('zoomOut').funct();
                mxEvent.consume(evt);
            }), Editor.zoomOutLargeImage, mxResources.get('zoomOut') + ' (Alt+Mousewheel)');

            addButton(mxUtils.bind(this, function (evt) {
                this.actions.get('zoomIn').funct();
                mxEvent.consume(evt);
            }), Editor.zoomInLargeImage, mxResources.get('zoomIn') + ' (Alt+Mousewheel)');

            addButton(mxUtils.bind(this, function (evt) {
                if (graph.isLightboxView()) {
                    if (graph.view.scale == 1) {
                        this.lightboxFit();
                    } else {
                        graph.zoomTo(1);
                    }

                    this.chromelessResize(false);
                } else {
                    this.chromelessResize(true);
                }

                mxEvent.consume(evt);
            }), Editor.actualSizeLargeImage, mxResources.get('fit'));

            // 悬停时更改工具栏不透明度
            var fadeThread = null;
            var fadeThread2 = null;

            var fadeOut = mxUtils.bind(this, function (delay) {
                if (fadeThread != null) {
                    window.clearTimeout(fadeThread);
                    fadeThread = null;
                }

                if (fadeThread2 != null) {
                    window.clearTimeout(fadeThread2);
                    fadeThread2 = null;
                }

                fadeThread = window.setTimeout(mxUtils.bind(this, function () {
                    mxUtils.setOpacity(this.chromelessToolbar, 0);
                    fadeThread = null;

                    fadeThread2 = window.setTimeout(mxUtils.bind(this, function () {
                        this.chromelessToolbar.style.display = 'none';
                        fadeThread2 = null;
                    }), 600);
                }), delay || 200);
            });

            var fadeIn = mxUtils.bind(this, function (opacity) {
                if (fadeThread != null) {
                    window.clearTimeout(fadeThread);
                    fadeThread = null;
                }

                if (fadeThread2 != null) {
                    window.clearTimeout(fadeThread2);
                    fadeThread2 = null;
                }

                this.chromelessToolbar.style.display = '';
                mxUtils.setOpacity(this.chromelessToolbar, opacity || 30);
            });

            if (urlParams['layers'] == '1') {
                this.layersDialog = null;

                var layersButton = addButton(mxUtils.bind(this, function (evt) {
                    if (this.layersDialog != null) {
                        this.layersDialog.parentNode.removeChild(this.layersDialog);
                        this.layersDialog = null;
                    } else {
                        this.layersDialog = graph.createLayersDialog();

                        mxEvent.addListener(this.layersDialog, 'mouseleave', mxUtils.bind(this, function () {
                            this.layersDialog.parentNode.removeChild(this.layersDialog);
                            this.layersDialog = null;
                        }));

                        var r = layersButton.getBoundingClientRect();

                        mxUtils.setPrefixedStyle(this.layersDialog.style, 'borderRadius', '5px');
                        this.layersDialog.style.position = 'fixed';
                        this.layersDialog.style.fontFamily = 'Helvetica,Arial';
                        this.layersDialog.style.backgroundColor = '#000000';
                        this.layersDialog.style.width = '160px';
                        this.layersDialog.style.padding = '4px 2px 4px 2px';
                        this.layersDialog.style.color = '#ffffff';
                        mxUtils.setOpacity(this.layersDialog, 70);
                        this.layersDialog.style.left = r.left + 'px';
                        this.layersDialog.style.bottom = parseInt(this.chromelessToolbar.style.bottom) +
                            this.chromelessToolbar.offsetHeight + 4 + 'px';

                        // 将对话框放在容器z-index之上
                        var style = mxUtils.getCurrentStyle(this.editor.graph.container);
                        this.layersDialog.style.zIndex = style.zIndex;

                        document.body.appendChild(this.layersDialog);
                    }

                    mxEvent.consume(evt);
                }), Editor.layersLargeImage, mxResources.get('layers'));

                // 根据内容显示/隐藏图层面板按钮
                var model = graph.getModel();

                model.addListener(mxEvent.CHANGE, function () {
                    layersButton.style.display = (model.getChildCount(model.root) > 1) ? '' : 'none';
                });
            }

            if (urlParams['openInSameWin'] != '1') {
                this.addChromelessToolbarItems(addButton);
            }

            if (this.editor.editButtonLink != null || this.editor.editButtonFunc != null) {
                addButton(mxUtils.bind(this, function (evt) {
                    if (this.editor.editButtonFunc != null) {
                        this.editor.editButtonFunc();
                    } else if (this.editor.editButtonLink == '_blank') {
                        this.editor.editAsNew(this.getEditBlankXml());
                    } else {
                        graph.openLink(this.editor.editButtonLink, 'editWindow');
                    }

                    mxEvent.consume(evt);
                }), Editor.editLargeImage, mxResources.get('edit'));
            }

            if (this.lightboxToolbarActions != null) {
                for (var i = 0; i < this.lightboxToolbarActions.length; i++) {
                    var lbAction = this.lightboxToolbarActions[i];
                    addButton(lbAction.fn, lbAction.icon, lbAction.tooltip);
                }
            }

            if (toolbarConfig.refreshBtn != null) {
                addButton(mxUtils.bind(this, function (evt) {
                    if (toolbarConfig.refreshBtn.url) {
                        window.location.href = toolbarConfig.refreshBtn.url;
                    } else {
                        window.location.reload();
                    }

                    mxEvent.consume(evt);
                }), Editor.refreshLargeImage, mxResources.get('refresh', null, 'Refresh'));
            }

            if (toolbarConfig.fullscreenBtn != null && window.self !== window.top) {
                addButton(mxUtils.bind(this, function (evt) {
                    if (toolbarConfig.fullscreenBtn.url) {
                        graph.openLink(toolbarConfig.fullscreenBtn.url);
                    } else {
                        graph.openLink(window.location.href);
                    }

                    mxEvent.consume(evt);
                }), Editor.fullscreenLargeImage, mxResources.get('openInNewWindow', null, 'Open in New Window'));
            }

            if ((toolbarConfig.closeBtn && window.self === window.top) ||
                (graph.lightbox && (urlParams['close'] == '1' || this.container != document.body))) {
                addButton(mxUtils.bind(this, function (evt) {
                    if (urlParams['close'] == '1' || toolbarConfig.closeBtn) {
                        window.close();
                    } else {
                        this.destroy();
                        mxEvent.consume(evt);
                    }
                }), Editor.closeLargeImage, mxResources.get('close') + ' (Escape)');
            }

            // 初始状态不可见
            this.chromelessToolbar.style.display = 'none';

            if (!graph.isViewer()) {
                mxUtils.setPrefixedStyle(this.chromelessToolbar.style, 'transform', 'translate(-50%,0)');
            }

            graph.container.appendChild(this.chromelessToolbar);

            mxEvent.addListener(graph.container, (mxClient.IS_POINTER) ? 'pointermove' : 'mousemove', mxUtils.bind(this, function (evt) {
                if (!mxEvent.isTouchEvent(evt)) {
                    if (!mxEvent.isShiftDown(evt)) {
                        fadeIn(30);
                    }

                    fadeOut();
                }
            }));

            mxEvent.addListener(this.chromelessToolbar, (mxClient.IS_POINTER) ? 'pointermove' : 'mousemove', function (evt) {
                mxEvent.consume(evt);
            });

            mxEvent.addListener(this.chromelessToolbar, 'mouseenter', mxUtils.bind(this, function (evt) {
                if (!mxEvent.isShiftDown(evt)) {
                    fadeIn(100);
                } else {
                    fadeOut();
                }
            }));

            mxEvent.addListener(this.chromelessToolbar, 'mousemove', mxUtils.bind(this, function (evt) {
                if (!mxEvent.isShiftDown(evt)) {
                    fadeIn(100);
                } else {
                    fadeOut();
                }

                mxEvent.consume(evt);
            }));

            mxEvent.addListener(this.chromelessToolbar, 'mouseleave', mxUtils.bind(this, function (evt) {
                if (!mxEvent.isTouchEvent(evt)) {
                    fadeIn(30);
                }
            }));

            // 为触摸设备显示/隐藏工具栏
            var tol = graph.getTolerance();

            graph.addMouseListener({
                startX: 0,
                startY: 0,
                scrollLeft: 0,
                scrollTop: 0,
                mouseDown: function (sender, me) {
                    this.startX = me.getGraphX();
                    this.startY = me.getGraphY();
                    this.scrollLeft = graph.container.scrollLeft;
                    this.scrollTop = graph.container.scrollTop;
                },
                mouseMove: function (sender, me) {},
                mouseUp: function (sender, me) {
                    if (mxEvent.isTouchEvent(me.getEvent())) {
                        if ((Math.abs(this.scrollLeft - graph.container.scrollLeft) < tol &&
                                Math.abs(this.scrollTop - graph.container.scrollTop) < tol) &&
                            (Math.abs(this.startX - me.getGraphX()) < tol &&
                                Math.abs(this.startY - me.getGraphY()) < tol)) {
                            if (parseFloat(ui.chromelessToolbar.style.opacity || 0) > 0) {
                                fadeOut();
                            } else {
                                fadeIn(30);
                            }
                        }
                    }
                }
            });
        } // end if toolbar

        // 安装对高亮和相对链接及锚点链接的处理
        if (!this.editor.editable) {
            this.addChromelessClickHandler();
        }
    } else if (this.editor.extendCanvas) {
        /**
         * 推测自动翻译以避免另一次重绘（见下文）。
         * 当只有图形缩放发生变化，或者页面可见且可见页面不发生变化时有效。
         */
        var graphViewValidate = graph.view.validate;
        graph.view.validate = function () {
            if (this.graph.container != null && mxUtils.hasScrollbars(this.graph.container)) {
                var pad = this.graph.getPagePadding();
                var size = this.graph.getPageSize();

                // 此处更新滚动条会在怪异模式下造成闪烁且不需要
                // if zoom method is always used to set the current scale on the graph.
                var tx = this.translate.x;
                var ty = this.translate.y;
                this.translate.x = pad.x - (this.x0 || 0) * size.width;
                this.translate.y = pad.y - (this.y0 || 0) * size.height;
            }

            graphViewValidate.apply(this, arguments);
        };

        if (!graph.isViewer()) {
            var graphSizeDidChange = graph.sizeDidChange;

            graph.sizeDidChange = function () {
                if (this.container != null && mxUtils.hasScrollbars(this.container)) {
                    var pages = this.getPageLayout();
                    var pad = this.getPagePadding();
                    var size = this.getPageSize();

                    // 更新图形的最小尺寸
                    var minw = Math.ceil(2 * pad.x + pages.width * size.width);
                    var minh = Math.ceil(2 * pad.y + pages.height * size.height);

                    var min = graph.minimumGraphSize;

                    // 稍后：修复IE怪异模式下滚动条大小的闪烁问题
                    // after delayed call in window.resize event handler
                    if (min == null || min.width != minw || min.height != minh) {
                        graph.minimumGraphSize = new mxRectangle(0, 0, minw, minh);
                    }

                    // 更新自动翻译以包含填充和图形尺寸
                    // var dx = pad.x - pages.x * size.width;
                    // var dy = pad.y - pages.y * size.height;
                    var dx = pad.x
                    var dy = pad.y;

                    if (!this.autoTranslate && (this.view.translate.x != dx || this.view.translate.y != dy)) {
                        this.autoTranslate = true;
                        this.view.x0 = pages.x;
                        this.view.y0 = pages.y;

                        // 注意：这会再次调用此方法。不幸的是，由于边界在验证后才知道且设置翻译会触发重新验证，
                        // 所以没有其他方法。应该将翻译/缩放到视图中。
                        var tx = graph.view.translate.x;
                        var ty = graph.view.translate.y;
                        graph.view.setTranslate(dx, dy);

                        // 稍后：修复小缩放时的舍入误差
                        graph.container.scrollLeft += Math.round((dx - tx) * graph.view.scale);
                        graph.container.scrollTop += Math.round((dy - ty) * graph.view.scale);

                        this.autoTranslate = false;

                        return;
                    }

                    graphSizeDidChange.apply(this, arguments);
                } else {
                    // 触发事件但不调用超类
                    this.fireEvent(new mxEventObject(mxEvent.SIZE, 'bounds', this.getGraphBounds()));
                }
            };
        }
    }

    // 在渲染进行时累积缩放因子
    // so that not the complete sequence of zoom steps must be painted
    var bgGroup = graph.view.getBackgroundPane();
    var mainGroup = graph.view.getDrawPane();
    graph.cumulativeZoomFactor = 1;
    var updateZoomTimeout = null;
    var cursorPosition = null;
    var scrollPosition = null;
    var forcedZoom = null;
    var filter = null;

    var scheduleZoom = function (delay) {
        if (updateZoomTimeout != null) {
            window.clearTimeout(updateZoomTimeout);
        }

        window.setTimeout(function () {
            if (!graph.isMouseDown || forcedZoom) {
                updateZoomTimeout = window.setTimeout(mxUtils.bind(this, function () {
                    if (graph.isFastZoomEnabled()) {
                        // 变换背景页面
                        if (graph.view.backgroundPageShape != null && graph.view.backgroundPageShape.node != null) {
                            mxUtils.setPrefixedStyle(graph.view.backgroundPageShape.node.style, 'transform-origin', null);
                            mxUtils.setPrefixedStyle(graph.view.backgroundPageShape.node.style, 'transform', null);
                        }

                        // 变换图形和背景图像
                        mainGroup.style.transformOrigin = '';
                        bgGroup.style.transformOrigin = '';

                        // Safari中变换重置不生效的解决方案
                        if (mxClient.IS_SF) {
                            mainGroup.style.transform = 'scale(1)';
                            bgGroup.style.transform = 'scale(1)';

                            window.setTimeout(function () {
                                mainGroup.style.transform = '';
                                bgGroup.style.transform = '';
                            }, 0)
                        } else {
                            mainGroup.style.transform = '';
                            bgGroup.style.transform = '';
                        }

                        // 显示交互元素
                        graph.view.getDecoratorPane().style.opacity = '';
                        graph.view.getOverlayPane().style.opacity = '';
                    }

                    var sp = new mxPoint(graph.container.scrollLeft, graph.container.scrollTop);
                    var offset = mxUtils.getOffset(graph.container);
                    var prev = graph.view.scale;
                    var dx = 0;
                    var dy = 0;

                    if (cursorPosition != null) {
                        dx = graph.container.offsetWidth / 2 - cursorPosition.x + offset.x;
                        dy = graph.container.offsetHeight / 2 - cursorPosition.y + offset.y;
                    }

                    graph.zoom(graph.cumulativeZoomFactor);
                    var s = graph.view.scale;

                    if (s != prev) {
                        if (scrollPosition != null) {
                            dx += sp.x - scrollPosition.x;
                            dy += sp.y - scrollPosition.y;
                        }

                        if (resize != null) {
                            ui.chromelessResize(false, null, dx * (graph.cumulativeZoomFactor - 1),
                                dy * (graph.cumulativeZoomFactor - 1));
                        }

                        if (mxUtils.hasScrollbars(graph.container) && (dx != 0 || dy != 0)) {
                            graph.container.scrollLeft -= dx * (graph.cumulativeZoomFactor - 1);
                            graph.container.scrollTop -= dy * (graph.cumulativeZoomFactor - 1);
                        }
                    }

                    if (filter != null) {
                        mainGroup.setAttribute('filter', filter);
                    }

                    graph.cumulativeZoomFactor = 1;
                    updateZoomTimeout = null;
                    scrollPosition = null;
                    cursorPosition = null;
                    forcedZoom = null;
                    filter = null;
                }), (delay != null) ? delay : ((graph.isFastZoomEnabled()) ? ui.wheelZoomDelay : ui.lazyZoomDelay));
            }
        }, 0);
    };

    var lastZoomEvent = Date.now();

    graph.lazyZoom = function (zoomIn, ignoreCursorPosition, delay) {
        // TODO：修复如果禁用滚动条则忽略光标位置的问题
        // 待完成：修复禁用滚动条时忽略光标位置的逻辑
        ignoreCursorPosition = ignoreCursorPosition || !graph.scrollbars;

        if (ignoreCursorPosition) {
            cursorPosition = new mxPoint(
                graph.container.offsetLeft + graph.container.clientWidth / 2,
                graph.container.offsetTop + graph.container.clientHeight / 2);
        }

        // 忽略事件以减少触摸和妙控鼠标的缩放速度
        if (Date.now() - lastZoomEvent < 15) {
            return;
        }

        lastZoomEvent = Date.now();

        // 在15%以下切换到5%的缩放步长
        if (zoomIn) {
            if (this.view.scale * this.cumulativeZoomFactor <= 0.15) {
                this.cumulativeZoomFactor *= (this.view.scale + 0.05) / this.view.scale;
            } else {
                // 在webkit中使用5%的缩放步长以获得更好的网格渲染
                // 并避免缩放步长的舍入误差
                this.cumulativeZoomFactor *= this.zoomFactor;
                this.cumulativeZoomFactor = Math.round(this.view.scale * this.cumulativeZoomFactor * 20) / 20 / this.view.scale;
            }
        } else {
            if (this.view.scale * this.cumulativeZoomFactor <= 0.15) {
                this.cumulativeZoomFactor *= (this.view.scale - 0.05) / this.view.scale;
            } else {
                // 在webkit中使用5%的缩放步长以获得更好的网格渲染
                // 并避免缩放步长的舍入误差
                this.cumulativeZoomFactor /= this.zoomFactor;
                this.cumulativeZoomFactor = Math.round(this.view.scale * this.cumulativeZoomFactor * 20) / 20 / this.view.scale;
            }
        }

        this.cumulativeZoomFactor = Math.max(0.05, Math.min(this.view.scale * this.cumulativeZoomFactor, 160)) / this.view.scale;

        if (graph.isFastZoomEnabled()) {
            if (filter == null && mainGroup.getAttribute('filter') != '') {
                filter = mainGroup.getAttribute('filter');
                mainGroup.removeAttribute('filter');
            }

            scrollPosition = new mxPoint(graph.container.scrollLeft, graph.container.scrollTop);

            var cx = (ignoreCursorPosition) ? graph.container.scrollLeft + graph.container.clientWidth / 2 :
                cursorPosition.x + graph.container.scrollLeft - graph.container.offsetLeft;
            var cy = (ignoreCursorPosition) ? graph.container.scrollTop + graph.container.clientHeight / 2 :
                cursorPosition.y + graph.container.scrollTop - graph.container.offsetTop;
            mainGroup.style.transformOrigin = cx + 'px ' + cy + 'px';
            mainGroup.style.transform = 'scale(' + this.cumulativeZoomFactor + ')';
            bgGroup.style.transformOrigin = cx + 'px ' + cy + 'px';
            bgGroup.style.transform = 'scale(' + this.cumulativeZoomFactor + ')';

            if (graph.view.backgroundPageShape != null && graph.view.backgroundPageShape.node != null) {
                var page = graph.view.backgroundPageShape.node;

                mxUtils.setPrefixedStyle(page.style, 'transform-origin',
                    ((ignoreCursorPosition) ? ((graph.container.clientWidth / 2 + graph.container.scrollLeft -
                        page.offsetLeft) + 'px') : ((cursorPosition.x + graph.container.scrollLeft -
                        page.offsetLeft - graph.container.offsetLeft) + 'px')) + ' ' +
                    ((ignoreCursorPosition) ? ((graph.container.clientHeight / 2 + graph.container.scrollTop -
                        page.offsetTop) + 'px') : ((cursorPosition.y + graph.container.scrollTop -
                        page.offsetTop - graph.container.offsetTop) + 'px')));
                mxUtils.setPrefixedStyle(page.style, 'transform',
                    'scale(' + this.cumulativeZoomFactor + ')');
            }

            graph.view.getDecoratorPane().style.opacity = '0';
            graph.view.getOverlayPane().style.opacity = '0';

            if (ui.hoverIcons != null) {
                ui.hoverIcons.reset();
            }
        }

        scheduleZoom(delay);
    };

    // 延迟重绘直到鼠标手势完成后
    mxEvent.addGestureListeners(graph.container, function (evt) {
        if (updateZoomTimeout != null) {
            window.clearTimeout(updateZoomTimeout);
        }
    }, null, function (evt) {
        if (graph.cumulativeZoomFactor != 1) {
            scheduleZoom(0);
        }
    });

    // 延迟重绘直到滚动结束后
    mxEvent.addListener(graph.container, 'scroll', function (evt) {
        if (updateZoomTimeout != null && !graph.isMouseDown && graph.cumulativeZoomFactor != 1) {
            scheduleZoom(0);
        }
    });

    mxEvent.addMouseWheelListener(mxUtils.bind(this, function (evt, up, force, cx, cy) {
        if (this.dialogs == null || this.dialogs.length == 0) {
            // 在禁用滚动条的情况下滚动
            if (!graph.scrollbars && !force && graph.isScrollWheelEvent(evt)) {
                var t = graph.view.getTranslate();
                var step = 40 / graph.view.scale;

                if (!mxEvent.isShiftDown(evt)) {
                    graph.view.setTranslate(t.x, t.y + ((up) ? step : -step));
                } else {
                    graph.view.setTranslate(t.x + ((up) ? -step : step), t.y);
                }
            } else if (force || graph.isZoomWheelEvent(evt)) {
                var source = mxEvent.getSource(evt);

                while (source != null) {
                    if (source == graph.container) {
                        graph.tooltipHandler.hideTooltip();
                        cursorPosition = (cx != null && cy != null) ? new mxPoint(cx, cy) :
                            new mxPoint(mxEvent.getClientX(evt), mxEvent.getClientY(evt));
                        forcedZoom = force;
                        graph.lazyZoom(up);
                        mxEvent.consume(evt);

                        return false;
                    }

                    source = source.parentNode;
                }
            }
        }
    }), graph.container);

    // 在iOS上对捏合手势使用快速缩放
    graph.panningHandler.zoomGraph = function (evt) {
        graph.cumulativeZoomFactor = evt.scale;
        graph.lazyZoom(evt.scale > 0, true);
        mxEvent.consume(evt);
    };
};

/**
 * 为无边框模式添加工具栏项目。
 * 添加打印按钮等基础工具栏功能。
 * 
 * @param {Function} addButton - 添加按钮的回调函数
 */
EditorUi.prototype.addChromelessToolbarItems = function (addButton) {
    addButton(mxUtils.bind(this, function (evt) {
        this.actions.get('print').funct();
        mxEvent.consume(evt);
    }), Editor.printLargeImage, mxResources.get('print'));
};

/**
 * 检查是否启用页面功能。
 * 根据编辑器状态和URL参数判断是否显示页面相关功能。
 * 
 * @returns {boolean} 是否启用页面功能
 */
EditorUi.prototype.isPagesEnabled = function () {
    return this.editor.editable || urlParams['hide-pages'] != '1';
};

/**
 * 创建临时图形实例用于屏幕外内容渲染。
 */
EditorUi.prototype.createTemporaryGraph = function (stylesheet) {
    var graph = new Graph(document.createElement('div'));
    graph.stylesheet.styles = mxUtils.clone(stylesheet.styles);
    graph.resetViewOnRootChange = false;
    graph.setConnectable(false);
    graph.gridEnabled = false;
    graph.autoScroll = false;
    graph.setTooltips(false);
    graph.setEnabled(false);

    // 容器必须在DOM中才能正确渲染HTML
    graph.container.style.visibility = 'hidden';
    graph.container.style.position = 'absolute';
    graph.container.style.overflow = 'hidden';
    graph.container.style.height = '1px';
    graph.container.style.width = '1px';

    return graph;
};

/**
 *
 */
EditorUi.prototype.addChromelessClickHandler = function () {
    var hl = urlParams['highlight'];

    // 为高亮颜色代码添加前导#
    if (hl != null && hl.length > 0) {
        hl = '#' + hl;
    }

    this.editor.graph.addClickHandler(hl);
};

/**
 *
 */
EditorUi.prototype.toggleFormatPanel = function (visible) {
    visible = (visible != null) ? visible : this.formatWidth == 0;

    if (this.format != null) {
        this.formatWidth = (visible) ? 240 : 0;
        this.formatContainer.style.display = (visible) ? '' : 'none';
        this.refresh();
        this.format.refresh();
        this.fireEvent(new mxEventObject('formatWidthChanged'));
    }
};

/**
 * 添加对标签中占位符的支持。
 * 启用在标签文本中使用占位符功能，提高图表的动态性。
 */
EditorUi.prototype.lightboxFit = function (maxHeight) {
    if (this.isDiagramEmpty()) {
        this.editor.graph.view.setScale(1);
    } else {
        var p = urlParams['border'];
        var border = 60;

        if (p != null) {
            border = parseInt(p);
        }

        // 稍后：使用初始图形边界以避免舍入误差
        this.editor.graph.maxFitScale = this.lightboxMaxFitScale;
        this.editor.graph.fit(border, null, null, null, null, null, maxHeight);
        this.editor.graph.maxFitScale = null;
    }
};

/**
 * 检查图表是否为空。
 * 判断当前图表中是否包含任何可见的单元格元素。
 *
 * @returns {boolean} 如果图表为空则返回true
 */
EditorUi.prototype.isDiagramEmpty = function () {
    var model = this.editor.graph.getModel();

    return model.getChildCount(model.root) == 1 && model.getChildCount(model.getChildAt(model.root, 0)) == 0;
};

/**
 * 用于允许特定事件的选择和上下文菜单的钩子方法。
 * 子类可以重写此方法来控制选择和右键菜单的行为。
 */
EditorUi.prototype.isSelectionAllowed = function (evt) {
    return mxEvent.getSource(evt).nodeName == 'SELECT' || (mxEvent.getSource(evt).nodeName == 'INPUT' &&
        mxUtils.isAncestorNode(this.formatContainer, mxEvent.getSource(evt)));
};

/**
 * 当浏览器窗口在未保存时关闭时安装对话框。
 * 在保存和图像导出期间必须禁用此功能。
 */
EditorUi.prototype.addBeforeUnloadListener = function () {
    // 如果浏览器窗口在未保存的情况下关闭，则安装对话框
    // 这必须在保存和图像导出期间禁用
    // 离开页面时页面操作
    window.onbeforeunload = mxUtils.bind(this, function () {
        console.log("onBeforeUnload");
        //const saveButton = window.document.getElementById("gesprite-save");
        //console.log(saveButton);
        if (!this.editor.isChromelessView()) {
            return this.onBeforeUnload();
        }
    });
};

/**
 * 为应用程序设置onbeforeunload事件。
 * 配置当用户尝试关闭或刷新页面时的处理逻辑。
 */
EditorUi.prototype.onBeforeUnload = function () {
    if (this.editor.modified) {
        return mxResources.get('allChangesLost');
    }
};

/**
 * 打开文件或从父窗口接收文件内容。
 * 尝试从父窗口获取文件数据并加载到编辑器中。
 */
EditorUi.prototype.open = function () {
    // Firefox中不允许跨域窗口访问，所以如果我们
    // 从另一个域打开，那么这将会失败。
    try {
        if (window.opener != null && window.opener.openFile != null) {
            window.opener.openFile.setConsumer(mxUtils.bind(this, function (xml, filename) {
                try {
                    var doc = mxUtils.parseXml(xml);
                    this.editor.setGraphXml(doc.documentElement);
                    this.editor.setModified(false);
                    this.editor.undoManager.clear();

                    if (filename != null) {
                        this.editor.setFilename(filename);
                        this.updateDocumentTitle();
                    }

                    return;
                } catch (e) {
                    mxUtils.alert(mxResources.get('invalidOrMissingFile') + ': ' + e.message);
                }
            }));
        }
    } catch (e) {
        // ignore
    }

    // 如果没有加载文件，则作为最后一步触发
    this.editor.graph.view.validate();

    // 只在特殊情况下需要，其中打开了初始文件
    // 并且minimumGraphSize发生变化，CSS必须更新。
    this.editor.graph.sizeDidChange();
    this.editor.fireEvent(new mxEventObject('resetGraphView'));
};

/**
 * 在指定位置显示弹出菜单。
 * 创建并显示一个新的弹出菜单，设置相关的事件处理。
 *
 * @param {Function} fn - 用于创建菜单项的函数
 * @param {number} x - 菜单显示的X坐标
 * @param {number} y - 菜单显示的Y坐标
 * @param {Event} evt - 触发事件对象
 */
EditorUi.prototype.showPopupMenu = function (fn, x, y, evt) {
    this.editor.graph.popupMenuHandler.hideMenu();

    var menu = new mxPopupMenu(fn);
    menu.div.className += ' geMenubarMenu';
    menu.smartSeparators = true;
    menu.showDisabled = true;
    menu.autoExpand = true;

    // 禁用自动展开并在隐藏时销毁菜单
    menu.hideMenu = mxUtils.bind(this, function () {
        mxPopupMenu.prototype.hideMenu.apply(menu, arguments);
        menu.destroy();
    });

    menu.popup(x, y, null, evt);

    // 允许通过点击文档来隐藏
    this.setCurrentMenu(menu);
};

/**
 * 设置当前菜单和元素。
 * 管理当前活动的菜单状态和关联的DOM元素。
 */
EditorUi.prototype.setCurrentMenu = function (menu, elt) {
    this.currentMenuElt = elt;
    this.currentMenu = menu;
};

/**
 * 重置当前菜单和元素。
 * 清除当前活动的菜单状态和关联的DOM元素。
 */
EditorUi.prototype.resetCurrentMenu = function () {
    this.currentMenuElt = null;
    this.currentMenu = null;
};

/**
 * 隐藏并销毁当前菜单。
 * 完全清理当前活动的菜单及其相关资源。
 */
EditorUi.prototype.hideCurrentMenu = function () {
    if (this.currentMenu != null) {
        this.currentMenu.hideMenu();
        this.resetCurrentMenu();
    }
};

/**
 * 更新文档标题。
 * 根据当前编辑状态和文件名更新浏览器标题栏。
 */
EditorUi.prototype.updateDocumentTitle = function () {
    var title = this.editor.getOrCreateFilename();

    if (this.editor.appName != null) {
        title += ' - ' + this.editor.appName;
    }

    document.title = title;
};

/**
 * 创建悬停图标系统。
 * 为图形元素创建悬停时显示的交互图标。
 */
EditorUi.prototype.createHoverIcons = function () {
    return new HoverIcons(this.editor.graph);
};

/**
 * 执行重做操作。
 * 如果当前正在编辑文本，则执行文本重做；否则执行图形重做。
 */
EditorUi.prototype.redo = function () {
    try {
        var graph = this.editor.graph;

        if (graph.isEditing()) {
            document.execCommand('redo', false, null);
        } else {
            this.editor.undoManager.redo();
        }
    } catch (e) {
        // ignore all errors
    }
};

/**
 * 执行撤销操作。
 * 如果当前正在编辑文本，则执行文本撤销；否则执行图形撤销。
 */
EditorUi.prototype.undo = function () {
    try {
        var graph = this.editor.graph;

        if (graph.isEditing()) {
            // 如果原生撤销不影响当前编辑值，则停止编辑并在图形上执行撤销
            var value = graph.cellEditor.textarea.innerHTML;
            document.execCommand('undo', false, null);

            if (value == graph.cellEditor.textarea.innerHTML) {
                graph.stopEditing(true);
                this.editor.undoManager.undo();
            }
        } else {
            this.editor.undoManager.undo();
        }
    } catch (e) {
        // ignore all errors
    }
};

/**
 * 检查是否可以执行重做操作。
 *
 * @returns {boolean} 如果可以重做则返回true
 */
EditorUi.prototype.canRedo = function () {
    return this.editor.graph.isEditing() || this.editor.undoManager.canRedo();
};

/**
 * 检查是否可以执行撤销操作。
 *
 * @returns {boolean} 如果可以撤销则返回true
 */
EditorUi.prototype.canUndo = function () {
    return this.editor.graph.isEditing() || this.editor.undoManager.canUndo();
};

/**
 *
 */
EditorUi.prototype.getEditBlankXml = function () {
    return mxUtils.getXml(this.editor.getGraphXml());
};

/**
 * 返回此编辑器无状态副本的URL。
 * 生成一个重置状态的编辑器链接，用于分享或新建操作。
 */
EditorUi.prototype.getUrl = function (pathname) {
    var href = (pathname != null) ? pathname : window.location.pathname;
    var parms = (href.indexOf('?') > 0) ? 1 : 0;

    // 为新的空白图表移除模板URL参数
    for (var key in urlParams) {
        if (parms == 0) {
            href += '?';
        } else {
            href += '&';
        }

        href += key + '=' + urlParams[key];
        parms++;
    }

    return href;
};

/**
 * 指定图形是否具有滚动条。
 * 控制图形容器是否显示滚动条以浏览大型图表。
 */
EditorUi.prototype.setScrollbars = function (value) {
    var graph = this.editor.graph;
    var prev = graph.container.style.overflow;
    graph.scrollbars = value;
    this.editor.updateGraphComponents();

    if (prev != graph.container.style.overflow) {
        graph.container.scrollTop = 0;
        graph.container.scrollLeft = 0;
        graph.view.scaleAndTranslate(1, 0, 0);
        this.resetScrollbars();
    }

    this.fireEvent(new mxEventObject('scrollbarsChanged'));
};

/**
 * 返回图形是否具有滚动条。
 * 检查当前图形容器是否启用了滚动条功能。
 */
EditorUi.prototype.hasScrollbars = function () {
    return this.editor.graph.scrollbars;
};

/**
 * @description 这个方法会重新计算元素超出，超出后自动调整位置
 * 重置滚动条的状态。
 * 恢复滚动条到初始状态，重新计算滚动区域的大小。
 */
EditorUi.prototype.resetScrollbars = function () {
    var graph = this.editor.graph;

    if (!this.editor.extendCanvas) {
        graph.container.scrollTop = 0;
        graph.container.scrollLeft = 0;

        if (!mxUtils.hasScrollbars(graph.container)) {
            graph.view.setTranslate(0, 0);
        }
    } else if (!this.editor.isChromelessView()) {
        if (mxUtils.hasScrollbars(graph.container)) {
            if (graph.pageVisible) {
                var pad = graph.getPagePadding();
                graph.container.scrollTop = Math.floor(pad.y - this.editor.initialTopSpacing) - 1;
                // 兜底居中
                graph.container.scrollLeft = Math.floor(Math.min(pad.x,
                    (graph.container.scrollWidth - graph.container.clientWidth) / 2)) - 1;

                // 将图形滚动到可见区域
                var bounds = graph.getGraphBounds();

                if (bounds.width > 0 && bounds.height > 0) {
                    if (bounds.x > graph.container.scrollLeft + graph.container.clientWidth * 0.9) {
                        graph.container.scrollLeft = Math.min(bounds.x + bounds.width - graph.container.clientWidth, bounds.x - 10);
                    }

                    if (bounds.y > graph.container.scrollTop + graph.container.clientHeight * 0.9) {
                        graph.container.scrollTop = Math.min(bounds.y + bounds.height - graph.container.clientHeight, bounds.y - 10);
                    }
                }
            } else {
                var bounds = graph.getGraphBounds();
                var width = Math.max(bounds.width, graph.scrollTileSize.width * graph.view.scale);
                var height = Math.max(bounds.height, graph.scrollTileSize.height * graph.view.scale);
                graph.container.scrollTop = Math.floor(Math.max(0, bounds.y - Math.max(20, (graph.container.clientHeight - height) / 4)));
                graph.container.scrollLeft = Math.floor(Math.max(0, bounds.x - Math.max(0, (graph.container.clientWidth - width) / 2)));
            }
        } else {
            var b = mxRectangle.fromRectangle((graph.pageVisible) ? graph.view.getBackgroundPageBounds() : graph.getGraphBounds())
            var tr = graph.view.translate;
            var s = graph.view.scale;
            b.x = b.x / s - tr.x;
            b.y = b.y / s - tr.y;
            b.width /= s;
            b.height /= s;

            var dy = (graph.pageVisible) ? 0 : Math.max(0, (graph.container.clientHeight - b.height) / 4);

            graph.view.setTranslate(Math.floor(Math.max(0,
                    (graph.container.clientWidth - b.width) / 2) - b.x + 2),
                Math.floor(dy - b.y + 1));
        }
    }
};

/**
 * 设置页面是否可见。
 * 控制图形的页面视图显示状态。
 *
 * @param {boolean} value - 是否显示页面视图
 */
EditorUi.prototype.setPageVisible = function (value) {
    // 不需要'页面视图'，这里直接置为false
    value = false

    var graph = this.editor.graph;
    var hasScrollbars = mxUtils.hasScrollbars(graph.container);
    var tx = 0;
    var ty = 0;

    if (hasScrollbars) {
        tx = graph.view.translate.x * graph.view.scale - graph.container.scrollLeft;
        ty = graph.view.translate.y * graph.view.scale - graph.container.scrollTop;
    }

    graph.pageVisible = value;
    graph.pageBreaksVisible = value;
    graph.preferPageSize = value;
    graph.view.validateBackground();

    // 针对可能的句柄偏移的解决方案
    if (hasScrollbars) {
        var cells = graph.getSelectionCells();
        graph.clearSelection();
        graph.setSelectionCells(cells);
    }

    // 调用updatePageBreaks
    graph.sizeDidChange();

    if (hasScrollbars) {
        graph.container.scrollLeft = graph.view.translate.x * graph.view.scale - tx;
        graph.container.scrollTop = graph.view.translate.y * graph.view.scale - ty;
    }

    this.fireEvent(new mxEventObject('pageViewChanged'));
};

/**
 * 类：ChangeGridColor
 *
 * 可撤销的网格颜色更改。
 * 处理网格颜色修改操作的撤销和重做功能。
 */
function ChangeGridColor(ui, color) {
    this.ui = ui;
    this.color = color;
};

/**
 * 执行新页面的选择。
 * 切换到指定的页面并更新相关的显示状态。
 */
ChangeGridColor.prototype.execute = function () {
    var temp = this.ui.editor.graph.view.gridColor;
    this.ui.setGridColor(this.color);
    this.color = temp;
};

// 为ChangeGridColor注册编解码器
(function () {
    var codec = new mxObjectCodec(new ChangeGridColor(), ['ui']);

    mxCodecRegistry.register(codec);
})();

/**
 * 更改类型。
 * 定义各种可撤销操作的类型标识。
 */
function ChangePageSetup(ui, color, image, format, pageScale) {
    this.ui = ui;
    this.color = color;
    this.previousColor = color;
    this.image = image;
    this.previousImage = image;
    this.format = format;
    this.previousFormat = format;
    this.pageScale = pageScale;
    this.previousPageScale = pageScale;

    // 必需，因为null是颜色和图像的有效值
    this.ignoreColor = false;
    this.ignoreImage = false;
}

/**
 * 可撤销页面重命名的实现。
 * 处理页面重命名操作的撤销和重做功能。
 */
ChangePageSetup.prototype.execute = function () {
    var graph = this.ui.editor.graph;

    if (!this.ignoreColor) {
        this.color = this.previousColor;
        var tmp = graph.background;
        this.ui.setBackgroundColor(this.previousColor);
        this.previousColor = tmp;
    }

    if (!this.ignoreImage) {
        this.image = this.previousImage;
        var tmp = graph.backgroundImage;
        this.ui.setBackgroundImage(this.previousImage);
        this.previousImage = tmp;
    }

    if (this.previousFormat != null) {
        if (!this.format) {
            this.format = this.previousFormat;
        }
        var tmp = graph.pageFormat;

        if (this.previousFormat.width != tmp.width ||
            this.previousFormat.height != tmp.height) {
            this.ui.setPageFormat(this.previousFormat);
            this.previousFormat = tmp;
        }
    }

    if (this.foldingEnabled != null && this.foldingEnabled != this.ui.editor.graph.foldingEnabled) {
        this.ui.setFoldingEnabled(this.foldingEnabled);
        this.foldingEnabled = !this.foldingEnabled;
    }

    if (this.previousPageScale != null) {
        var currentPageScale = this.ui.editor.graph.pageScale;

        if (this.previousPageScale != currentPageScale) {
            this.ui.setPageScale(this.previousPageScale);
            this.previousPageScale = currentPageScale;
        }
    }
};

// 为ChangePageSetup注册编解码器
(function () {
    var codec = new mxObjectCodec(new ChangePageSetup(), ['ui', 'previousColor', 'previousImage', 'previousFormat', 'previousPageScale']);

    codec.afterDecode = function (dec, node, obj) {
        obj.previousColor = obj.color;
        obj.previousImage = obj.image;
        obj.previousFormat = obj.format;
        obj.previousPageScale = obj.pageScale;

        if (obj.foldingEnabled != null) {
            obj.foldingEnabled = !obj.foldingEnabled;
        }

        return obj;
    };

    mxCodecRegistry.register(codec);
})();

/**
 * 设置图表的背景颜色。
 * 更新图形背景色并重新验证背景显示。
 *
 * @param {string} value - 背景颜色的值（如十六进制颜色值）
 */
EditorUi.prototype.setBackgroundColor = function (value) {
    this.editor.graph.background = value;
    this.editor.graph.view.validateBackground();

    this.fireEvent(new mxEventObject('backgroundColorChanged'));
};

/**
 * 设置是否启用折叠功能。
 * 控制图形中组的展开/折叠功能。
 *
 * @param {boolean} value - 是否启用折叠功能
 */
EditorUi.prototype.setFoldingEnabled = function (value) {
    this.editor.graph.foldingEnabled = value;
    this.editor.graph.view.revalidate();

    this.fireEvent(new mxEventObject('foldingEnabledChanged'));
};

/**
 * 设置页面格式。
 * 更新图形的页面尺寸和格式设置。
 *
 * @param {mxRectangle} value - 页面格式对象，包含宽度和高度
 */
EditorUi.prototype.setPageFormat = function (value) {
    this.editor.graph.pageFormat = value;

    if (!this.editor.graph.pageVisible) {
        this.actions.get('pageView').funct();
    } else {
        this.editor.graph.view.validateBackground();
        this.editor.graph.sizeDidChange();
    }

    this.fireEvent(new mxEventObject('pageFormatChanged'));
};

/**
 * 设置页面比例。
 * 调整图形的页面缩放比例，影响整体显示大小。
 */
EditorUi.prototype.setPageScale = function (value) {
    this.editor.graph.pageScale = value;

    if (!this.editor.graph.pageVisible) {
        this.actions.get('pageView').funct();
    } else {
        this.editor.graph.view.validateBackground();
        this.editor.graph.sizeDidChange();
    }

    this.fireEvent(new mxEventObject('pageScaleChanged'));
};

/**
 * 设置网格颜色。
 * 更改图形背景网格的显示颜色。
 */
EditorUi.prototype.setGridColor = function (value) {
    this.editor.graph.view.gridColor = value;
    this.editor.graph.view.validateBackground();
    this.fireEvent(new mxEventObject('gridColorChanged'));
};

/**
 * 添加撤销监听器。
 * 为撤销管理器添加事件监听器，以便在历史记录变化时更新UI状态。
 */
EditorUi.prototype.addUndoListener = function () {
    var undo = this.actions.get('undo');
    var redo = this.actions.get('redo');

    var undoMgr = this.editor.undoManager;

    var undoListener = mxUtils.bind(this, function () {
        // undo.setEnabled(this.canUndo.call(this.editor ? this :  myEditor));
        // redo.setEnabled(this.canRedo.call(this.editor ? this :  myEditor));
        undo.setEnabled(this.canUndo());
        redo.setEnabled(this.canRedo());
    });

    undoMgr.addListener(mxEvent.ADD, undoListener);
    undoMgr.addListener(mxEvent.UNDO, undoListener);
    undoMgr.addListener(mxEvent.REDO, undoListener);
    undoMgr.addListener(mxEvent.CLEAR, undoListener);

    // 覆盖单元格编辑器以更新动作状态
    var cellEditorStartEditing = this.editor.graph.cellEditor.startEditing;

    this.editor.graph.cellEditor.startEditing = function () {
        cellEditorStartEditing.apply(this, arguments);
        undoListener();
    };

    var cellEditorStopEditing = this.editor.graph.cellEditor.stopEditing;

    this.editor.graph.cellEditor.stopEditing = function (cell, trigger) {
        cellEditorStopEditing.apply(this, arguments);
        undoListener();
    };

    // 一次性更新按钮状态
    undoListener();
};

/**
 * 根据选择更新给定工具栏项目的状态。
 * 根据当前选中的元素更新相关工具栏按钮的启用/禁用状态。
 */
EditorUi.prototype.updateActionStates = function () {
    var graph = this.editor.graph;
    var selected = !graph.isSelectionEmpty();
    var vertexSelected = false;
    var groupSelected = false;
    var edgeSelected = false;

    var cells = graph.getSelectionCells();

    if (cells != null) {
        for (var i = 0; i < cells.length; i++) {
            var cell = cells[i];

            if (graph.getModel().isEdge(cell)) {
                edgeSelected = true;
            }

            if (graph.getModel().isVertex(cell)) {
                vertexSelected = true;

                if (graph.getModel().getChildCount(cell) > 0 ||
                    graph.isContainer(cell)) {
                    groupSelected = true;
                }
            }

            if (edgeSelected && vertexSelected) {
                break;
            }
        }
    }

    // 更新动作状态
    var actions = ['cut', 'copy', 'bold', 'italic', 'underline', 'delete', 'duplicate',
        'editStyle', 'editTooltip', 'editLink', 'backgroundColor', 'borderColor',
        'edit', 'toFront', 'toBack', 'lockUnlock', 'solid', 'dashed', 'pasteSize',
        'dotted', 'fillColor', 'gradientColor', 'shadow', 'fontColor',
        'formattedText', 'rounded', 'toggleRounded', 'sharp', 'strokeColor'
    ];

    for (var i = 0; i < actions.length; i++) {
        this.actions.get(actions[i]).setEnabled(selected);
    }
    // 格式刷是否启用
    this.actions.get('painter').setEnabled(graph.getSelectionCount() == 1);
    this.actions.get('setAsDefaultStyle').setEnabled(graph.getSelectionCount() == 1);
    this.actions.get('clearWaypoints').setEnabled(!graph.isSelectionEmpty());
    this.actions.get('copySize').setEnabled(graph.getSelectionCount() == 1);
    this.actions.get('turn').setEnabled(!graph.isSelectionEmpty());
    this.actions.get('curved').setEnabled(edgeSelected);
    this.actions.get('rotation').setEnabled(vertexSelected);
    this.actions.get('wordWrap').setEnabled(vertexSelected);
    this.actions.get('autosize').setEnabled(vertexSelected);
    var oneVertexSelected = vertexSelected && graph.getSelectionCount() == 1;
    this.actions.get('group').setEnabled(graph.getSelectionCount() > 1 ||
        (oneVertexSelected && !graph.isContainer(graph.getSelectionCell())));
    this.actions.get('ungroup').setEnabled(groupSelected);
    this.actions.get('removeFromGroup').setEnabled(oneVertexSelected &&
        graph.getModel().isVertex(graph.getModel().getParent(graph.getSelectionCell())));

    const isTimeaxis = this.sidebar && this.sidebar.hasTimeaxis
    // 更新菜单状态
    var state = graph.view.getState(graph.getSelectionCell());
    this.menus.get('navigation').setEnabled(selected || graph.view.currentRoot != null);
    this.actions.get('collapsible').setEnabled(vertexSelected &&
        (graph.isContainer(graph.getSelectionCell()) || graph.model.getChildCount(graph.getSelectionCell()) > 0));
    this.actions.get('home').setEnabled(graph.view.currentRoot != null);
    this.actions.get('exitGroup').setEnabled(graph.view.currentRoot != null);
    this.actions.get('enterGroup').setEnabled(graph.getSelectionCount() == 1 && graph.isValidRoot(graph.getSelectionCell()));
    var foldable = graph.getSelectionCount() == 1 && graph.isCellFoldable(graph.getSelectionCell());
    this.actions.get('expand').setEnabled(foldable);
    this.actions.get('collapse').setEnabled(foldable);
    this.actions.get('editLink').setEnabled(graph.getSelectionCount() == 1);
    this.actions.get('openLink').setEnabled(graph.getSelectionCount() == 1 &&
        graph.getLinkForCell(graph.getSelectionCell()) != null);
    this.actions.get('guides').setEnabled(graph.isEnabled());
    this.actions.get('grid').setEnabled(!this.editor.chromeless || this.editor.editable);

    var unlocked = graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent());
    this.menus.get('layout').setEnabled(unlocked && !isTimeaxis);
    this.menus.get('insert').setEnabled(unlocked);
    this.menus.get('direction').setEnabled(unlocked && vertexSelected);
    this.menus.get('align').setEnabled(unlocked && vertexSelected && graph.getSelectionCount() > 1);
    this.menus.get('distribute').setEnabled(unlocked && vertexSelected && graph.getSelectionCount() > 1);
    this.actions.get('selectVertices').setEnabled(unlocked);
    this.actions.get('selectEdges').setEnabled(unlocked);
    this.actions.get('selectAll').setEnabled(unlocked);
    this.actions.get('selectNone').setEnabled(unlocked);
    this.menus.get('edgeShape').setEnabled(edgeSelected && !vertexSelected)
    this.menus.get('edgeStyle').setEnabled(edgeSelected && !vertexSelected)
    this.menus.get('lineType').setEnabled(edgeSelected && !vertexSelected)
    this.menus.get('arrowType').setEnabled(edgeSelected && !vertexSelected)
    // 时间轴禁用对局
    this.menus.get('alignType').setEnabled(selected && !isTimeaxis)

    if (this.toolbar) {
        this.updatePasteActionStates();
    }
};

/**
 * 零偏移点。
 * 表示坐标原点(0,0)的点对象，用于计算相对位置。
 */
EditorUi.prototype.zeroOffset = new mxPoint(0, 0);

/**
 * 获取图表容器的偏移量。
 * 返回图表容器相对于其父容器的偏移位置。
 *
 * @returns {mxPoint} 偏移量点对象
 */
EditorUi.prototype.getDiagramContainerOffset = function () {
    return this.zeroOffset;
};

/**
 * 刷新编辑器UI布局和尺寸。
 * 根据容器大小变化重新计算和调整所有UI组件的位置和大小。
 *
 * @param {boolean} sizeDidChange - 容器尺寸是否发生了变化
 */
EditorUi.prototype.refresh = function (sizeDidChange) {
    sizeDidChange = (sizeDidChange != null) ? sizeDidChange : true;

    var w = this.container.clientWidth;
    var h = this.container.clientHeight;

    if (this.container == document.body) {
        w = document.body.clientWidth || document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
    }

    // iOS上bug的解决方案，见
    // http://stackoverflow.com/questions/19012135/ios-7-ipad-safari-landscape-innerheight-outerheight-layout-issue
    // FIXME：如果页脚可见则修复
    // 待修复：页脚可见时的高度计算修复
    var off = 0;

    if (mxClient.IS_IOS && !window.navigator.standalone) {
        if (window.innerHeight != document.documentElement.clientHeight) {
            off = document.documentElement.clientHeight - window.innerHeight;
            window.scrollTo(0, 0);
        }
    }

    var effHsplitPosition = Math.max(0, Math.min(this.hsplitPosition, w - this.splitSize - 20));
    var tmp = 0;

    if (this.menubar != null) {
        this.menubarContainer.style.height = this.menubarHeight + 'px';
        tmp += this.menubarHeight;
    }

    if (this.toolbar != null) {
        this.toolbarContainer.style.top = this.menubarHeight + 'px';
        this.toolbarContainer.style.height = this.toolbarHeight + 'px';
        tmp += this.toolbarHeight;
    }

    if (tmp > 0) {
        tmp += 1;
    }

    var sidebarFooterHeight = 0;

    if (this.sidebarFooterContainer != null) {
        var bottom = this.footerHeight + off;
        sidebarFooterHeight = Math.max(0, Math.min(h - tmp - bottom, this.sidebarFooterHeight));
        this.sidebarFooterContainer.style.width = effHsplitPosition + 'px';
        this.sidebarFooterContainer.style.height = sidebarFooterHeight + 'px';
        this.sidebarFooterContainer.style.bottom = bottom + 'px';
    }

    var fw = (this.format != null) ? this.formatWidth : 0;
    this.sidebarContainer.style.top = tmp + 'px';
    // sysml下 sidebarContainer和sidebarStructureContainer各占一半
    this.sidebarContainer.style.width = effHsplitPosition + 'px';
    this.sidebarScanContainer.style.top = tmp + 'px';
    if (this.sidebarScanContainer) {
        this.sidebarScanContainer.style.width = effHsplitPosition + 'px';
    }
    if (window.sidebarScan) {
        window.sidebarScan.container.style.width = effHsplitPosition + 'px';
    }
    this.sidebarStructureContainer.style.top = tmp + 'px';
    this.sidebarStructureContainer.style.width = effHsplitPosition / 2 + 'px';
    this.formatContainer.style.top = tmp + 'px';
    this.formatContainer.style.width = fw + 'px';
    this.formatContainer.style.display = (this.format != null) ? '' : 'none';

    var diagContOffset = this.getDiagramContainerOffset();
    var contLeft = (this.hsplit.parentNode != null) ? (effHsplitPosition + this.splitSize) : 0;
    this.diagramContainer.style.left = (contLeft + diagContOffset.x) + 'px';
    this.diagramContainer.style.top = (tmp + diagContOffset.y) + 'px';

    this.footerContainer.style.height = this.footerHeight + 'px';
    this.hsplit.style.top = this.sidebarContainer.style.top;
    this.hsplit.style.bottom = (this.footerHeight + off) + 'px';
    this.hsplit.style.left = effHsplitPosition + 'px';
    this.footerContainer.style.display = (this.footerHeight == 0) ? 'none' : '';

    if (this.tabContainer != null) {
        this.tabContainer.style.left = contLeft + 'px';
    }

    if (this.footerHeight > 0) {
        this.footerContainer.style.bottom = off + 'px';
    }

    this.diagramContainer.style.right = fw + 'px';
    var th = 0;

    if (this.tabContainer != null) {
        this.tabContainer.style.bottom = (this.footerHeight + off) + 'px';
        this.tabContainer.style.right = this.diagramContainer.style.right;
        th = this.tabContainer.clientHeight;
    }

    this.sidebarContainer.style.bottom = (this.footerHeight + sidebarFooterHeight + off) + 'px';
    this.sidebarScanContainer.style.bottom = (this.footerHeight + sidebarFooterHeight + off) + 'px';
    this.sidebarStructureContainer.style.bottom = (this.footerHeight + sidebarFooterHeight + off) + 'px';

    this.formatContainer.style.bottom = (this.footerHeight + off) + 'px';
    this.diagramContainer.style.bottom = (this.footerHeight + off + th) + 'px';

    if (sizeDidChange) {
        this.editor.graph.sizeDidChange();
    }
};

/**
 * 创建所需的标签容器。
 * 初始化页面标签管理系统的容器元素。
 */
EditorUi.prototype.createTabContainer = function () {
    return null;
};

/**
 * 创建编辑器UI的主要DOM容器元素。
 * 初始化菜单栏、工具栏、侧边栏、格式面板、图表容器等所有UI组件的容器。
 */
EditorUi.prototype.createDivs = function () {

    this.menubarContainer = this.createDiv('geMenubarContainer');
    this.toolbarContainer = this.createDiv('geToolbarContainer');
    //this.sidebarContainer = this.createDiv('geSidebarContainer');
    // 创建 id=sidebarContainer div
    this.sidebarContainer = this.createDivId('geSidebarContainer', 'sidebarContainer');
    this.sidebarScanContainer = this.createDivId('geSidebarScanContainer', 'sidebarScanContainer');
    this.sidebarStructureContainer = this.createDivId('geSidebarScanContainer', 'sidebarStructrueContainer');
    this.formatContainer = this.createDiv('geSidebarContainer geFormatContainer');
    //
    this.diagramContainer = this.createDivId('geDiagramContainer', 'geDiagramContainer');

    this.footerContainer = this.createDiv('geFooterContainer');
    // this.hsplit = this.createDiv('geHsplit');
    this.hsplit = this.createDivId('geHsplit', 'gehsplit');
    this.hsplit.setAttribute('title', mxResources.get('collapseExpand'));

    // 为容器设置静态样式
    this.menubarContainer.style.top = '0px';
    this.menubarContainer.style.left = '0px';
    this.menubarContainer.style.right = '0px';
    this.toolbarContainer.style.left = '0px';
    this.toolbarContainer.style.right = '0px';
    // sysml下 图元在右侧 结构在左侧
    this.sidebarContainer.style.left = '0px';
    this.sidebarScanContainer.style.left = '0px';
    this.sidebarStructureContainer.style.left = '0px';
    this.formatContainer.id = "formatcontainer_div";
    this.formatContainer.style.right = '0px';
    this.formatContainer.style.zIndex = '1';
    this.diagramContainer.style.right = ((this.format != null) ? this.formatWidth : 0) + 'px';
    this.footerContainer.style.left = '0px';
    this.footerContainer.style.right = '0px';
    this.footerContainer.style.bottom = '0px';
    this.footerContainer.style.zIndex = mxPopupMenu.prototype.zIndex - 2;
    this.hsplit.style.width = this.splitSize + 'px';
    this.sidebarFooterContainer = null;
    // this.createSidebarFooterContainer();

    if (this.sidebarFooterContainer) {
        this.sidebarFooterContainer.style.left = '0px';
    }

    if (!this.editor.chromeless) {
        this.tabContainer = this.createTabContainer();
    } else {
        this.diagramContainer.style.border = 'none';
    }
};

/**
 * 侧边栏页脚容器的钩子方法。此实现返回null。
 * 子类可以重写此方法来自定义侧边栏页脚区域。
 */
EditorUi.prototype.createSidebarFooterContainer = function () {
    return null;
};

/**
 * 创建和初始化完整的用户界面。
 * 设置菜单栏、工具栏、侧边栏、状态栏等所有UI组件，并配置事件处理。
 */
EditorUi.prototype.createUi = function () {

    //初始化UI
    // 创建菜单栏
    if (window.graphEditable) {
        this.menubar = (this.editor.chromeless) ? null : this.menus.createMenubar(this.createDiv('geMenubar'));
    }

    if (this.menubar != null) {
        this.menubarContainer.appendChild(this.menubar.container);
    }

    // 在菜单栏中添加状态栏
    if (this.menubar != null) {
        this.statusContainer = this.createStatusContainer();

        // 将状态栏连接到编辑器状态
        this.editor.addListener('statusChanged', mxUtils.bind(this, function () {
            this.setStatusText(this.editor.getStatus());
        }));

        this.setStatusText(this.editor.getStatus());
        this.menubar.container.appendChild(this.statusContainer);

        // 插入到DOM中
        this.container.appendChild(this.menubarContainer);
    }

    // 创建侧边栏
    if (window.graphEditable) {
        if (!isFzPage) {
            this.sidebar = (this.editor.chromeless) ? null : this.createSidebar(this.sidebarContainer);
        }
        this.graphEvent = this.createGraphEvent(this)

        this.guideEvent = this.createGuideEvent(this);

        if (window.isGuideDisabled) {
            this.editor.graph.setEnabled(false);
        }

        // dom是否已经渲染了
        const sidebarScanContainerDom = document.querySelector('#sidebarScanContainer')

        if (!sidebarScanContainerDom) {
            window.sidebarScan = this.sidebarScan = this.createSidebarScan(this.sidebarScanContainer)
        }

        if (this.sidebar != null) {
            this.container.appendChild(this.sidebarContainer);
        }
        if (!this.sidebarScan != null) {
            if (!sidebarScanContainerDom) {
                this.container.appendChild(this.sidebarScanContainer);
            }
        }

    }

    // 创建格式侧边栏
    if (window.graphEditable) {
        if (!this.format) {
            this.format = (this.editor.chromeless || !this.formatEnabled) ? null : this.createFormat(this.formatContainer);
            this.container.appendChild(this.formatContainer);

            this.toggleFormatPanel(false)
        }
    }

    // 创建页脚
    var footer = (this.editor.chromeless) ? null : this.createFooter();

    if (footer != null) {
        this.footerContainer.appendChild(footer);
        this.container.appendChild(this.footerContainer);
    }

    if (this.sidebar != null && this.sidebarFooterContainer) {
        this.container.appendChild(this.sidebarFooterContainer);
    }

    this.container.appendChild(this.diagramContainer);

    if (this.container != null && this.tabContainer != null) {
        this.container.appendChild(this.tabContainer);
    }

    // 创建工具栏
    if (window.graphEditable) {
        if (!isFzPage) {
            this.toolbar = (this.editor.chromeless) ? null : this.createToolbar(this.createDiv('geToolbar'));
        }
    }
    if (this.toolbar != null) {
        this.toolbarContainer.appendChild(this.toolbar.container);
        this.container.appendChild(this.toolbarContainer);
    }

    // 水平分割
    if (this.sidebar != null) {
        this.container.appendChild(this.hsplit);
        this.addSplitHandler(this.hsplit, true, 0, mxUtils.bind(this, function (value) {
            this.hsplitPosition = value;
            this.refresh();
        }));
    }

    if (window.isFzPage) {
        this.editor.graph.setEnabled(false)
    } else {
        this.editor.graph.setEnabled(window.graphEditable)
    }
};

/**
 * 更新sider宽度
 */
EditorUi.prototype.updateWidth = function (e = true) {
    if (window.isSysml) {
        this.hsplitPosition = e ? 400 : 200;
        this.refresh();
    }
};

/**
 * 创建状态容器。
 * 为状态栏创建并返回一个新的DOM容器元素。
 *
 * @returns {Element} 新创建的状态容器元素
 */
EditorUi.prototype.createStatusContainer = function () {
    var container = document.createElement('a');
    container.className = 'geItem geStatus';
    return container;
};

/**
 * 设置状态文本。
 * 在状态栏容器中显示指定的状态信息。
 *
 * @param {string} value - 要显示的状态文本
 */
EditorUi.prototype.setStatusText = function (value) {
    this.statusContainer.innerHTML = value;
};

/**
 * 创建工具栏。
 * 在指定的容器中创建工具栏组件。
 *
 * @param {Element} container - 工具栏容器元素
 * @returns {Toolbar} 新创建的工具栏实例
 */
EditorUi.prototype.createToolbar = function (container) {
    return new Toolbar(this, container);
};

/**
 * 创建侧边栏。
 * 在指定的容器中创建侧边栏组件。
 *
 * @param {Element} container - 侧边栏容器元素
 * @returns {Sidebar} 新创建的侧边栏实例
 */
EditorUi.prototype.createSidebar = function (container) {
    return new Sidebar(this, container);
};

/**
 * 创建图形事件处理器。
 * 创建并返回用于处理图形相关事件的事件处理器实例。
 *
 * @returns {GraphEvent} 新创建的图形事件处理器
 */
EditorUi.prototype.createGraphEvent = function () {
    return new GraphEvent(this);
};

/**
 * 创建引导事件处理器。
 * 创建并返回用于处理引导线和对齐辅助相关事件的处理器实例。
 *
 * @returns {GuideEvent} 新创建的引导事件处理器
 */
EditorUi.prototype.createGuideEvent = function () {
    return new GuideEvent(this);
};

/**
 * 更新
 */
EditorUi.prototype.updateSidebar = function () {
    this.editor.graph.setEnabled(!window.isGuideDisabled);

    if (!window.graphEditable) {
        if (this.menubar != null) {
            this.menubar.destroy();
            this.menubar = null;
        }

        if (this.toolbar != null) {
            this.toolbar.destroy();
            this.toolbar = null;
        }

        if (this.sidebar != null) {
            this.sidebar.destroy();
            this.sidebar = null;
        }
        var c = [this.menubarContainer, this.toolbarContainer, this.sidebarContainer, this.hsplit, this.formatContainer];

        for (var i = 0; i < c.length; i++) {
            if (c[i] != null && c[i].parentNode != null) {
                c[i].parentNode.removeChild(c[i]);
            }
        }
        this.format = null
    } else {
        this.editor.graph.popupMenuHandler.hideMenu()
        var c = [this.menubarContainer, this.toolbarContainer, this.sidebarContainer, this.hsplit, this.formatContainer];

        for (var i = 0; i < c.length; i++) {
            if (c[i] != null) {
                c[i].innerHTML = ''
            }
        }

        this.menubar = (this.editor.chromeless) ? null : this.menus.createMenubar(this.createDiv('geMenubar'));
        if (this.menubar != null) {
            this.menubarContainer.appendChild(this.menubar.container);
        }
        if (!isFzPage) {
            this.sidebar = (this.editor.chromeless) ? null : this.createSidebar(this.sidebarContainer);
        }
        if (this.sidebar != null) {
            this.container.appendChild(this.sidebarContainer);
            this.container.appendChild(this.hsplit);
            this.addSplitHandler(this.hsplit, true, 0, mxUtils.bind(this, function (value) {
                this.hsplitPosition = value;
                this.refresh();
            }));
        }

        if (!isFzPage) {
            this.toolbar = (this.editor.chromeless) ? null : this.createToolbar(this.createDiv('geToolbar'));
        }
        if (this.toolbar != null) {
            this.toolbarContainer.appendChild(this.toolbar.container);
            this.container.appendChild(this.toolbarContainer);
        }

        if (!this.format) {
            this.format = (this.editor.chromeless || !this.formatEnabled) ? null : this.createFormat(this.formatContainer);
            this.format.init();
            this.format.refresh();
            this.container.appendChild(this.formatContainer);

            this.toggleFormatPanel(false)
        }
    }
    if (window.isFzPage) {
        this.editor.graph.setEnabled(false)
    } else {
        this.editor.graph.setEnabled(window.graphEditable)
    }

    this.refresh()

    // const sidebarContainerDom = document.querySelector('.geSidebarContainer')
    // sidebarContainerDom.innerHTML = ''
    // new Sidebar(window.myEditor, sidebarContainerDom);
}

/**
 * 创建一个侧边浏览窗口
 */
EditorUi.prototype.createSidebarScan = function (container) {
    return new SidebarScan(this, container);
};

/**
 * 创建一个侧边对象结构
 */
EditorUi.prototype.createSidebarStructure = function (container) {
    return new SidebarStructure(this, container);
};

/**
 * 为给定容器创建新的侧边栏。
 * 初始化并配置编辑器的左侧边栏组件。
 *
 * @param {Element} container - 侧边栏容器元素
 * @returns {Sidebar} 新创建的侧边栏实例
 */
EditorUi.prototype.createFormat = function (container) {
    return new Format(this, container);
};

/**
 * 创建并返回新的页脚。
 * 初始化编辑器底部的状态栏和其他页脚元素。
 *
 * @returns {Element} 新创建的页脚元素
 */
EditorUi.prototype.createFooter = function () {
    return this.createDiv('geFooter');
};

/**
 * 为工具栏容器创建实际的工具栏。
 * 生成一个简单的div元素作为工具栏容器。
 *
 * @param {string} classname - CSS类名
 * @returns {Element} 创建的工具栏元素
 */
EditorUi.prototype.createDiv = function (classname) {
    var elt = document.createElement('div');
    elt.className = classname;
    return elt;
};

/**
 * 带ID的 div
 * @param classname
 * @param id
 * @returns {HTMLDivElement}
 */
/**
 * 创建带有ID的div元素。
 * 创建一个具有指定CSS类名和ID的div元素。
 *
 * @param {string} classname - CSS类名
 * @param {string} id - 元素ID
 * @returns {Element} 创建的div元素
 */
EditorUi.prototype.createDivId = function (classname, id) {
    var elt = document.createElement('div');
    elt.id = id;
    elt.className = classname;
    return elt;
};

/**
 * 创建侧边栏容器div元素。
 * 为侧边栏创建一个具有特定样式和特性的容器元素。
 *
 * @param {string} classname - CSS类名
 * @param {string} id - 元素ID
 * @returns {Element} 创建的侧边栏容器元素
 */
EditorUi.prototype.createSidebarContainerDiv = function (classname, id) {

    // const div = this.createDivId(classname, id);
    // const table = document.createElement("table");
    // const tbody = document.createElement("tbody");
    // const tr = document.createElement("tr");
    // const td1 = document.createElement("td");
    // const td2 = document.createElement("td");
    // td1.appendChild(div);
    // tr.appendChild(td1);
    // tr.appendChild(td2);
    // tbody.appendChild(tr);
    // table.appendChild(tbody);

    return this.createDivId(classname, id);

};

/**
 * 更新给定撤销/重做项目的状态。
 * 根据历史记录状态更新相关按钮的可用性。
 */
/**
 * 为元素添加分割处理程序。
 * 为指定元素添加拖拽分割功能，允许用户调整布局大小。
 *
 * @param {Element} elt - 要添加分割功能的元素
 * @param {boolean} horizontal - 是否为水平分割
 * @param {number} dx - 分割的偏移量
 * @param {Function} onChange - 大小变化时的回调函数
 */
EditorUi.prototype.addSplitHandler = function (elt, horizontal, dx, onChange) {
    var start = null;
    var initial = null;
    var ignoreClick = true;
    var last = null;

    // 禁用IE10及更高版本中的内置平移和缩放功能
    if (mxClient.IS_POINTER) {
        elt.style.touchAction = 'none';
    }

    var getValue = mxUtils.bind(this, function () {
        var result = parseInt(((horizontal) ? elt.style.left : elt.style.bottom));

        // 考虑隐藏的页脚
        if (!horizontal) {
            result = result + dx - this.footerHeight;
        }

        return result;
    });

    function moveHandler(evt) {
        if (start != null) {
            var pt = new mxPoint(mxEvent.getClientX(evt), mxEvent.getClientY(evt));
            onChange(Math.max(0, initial + ((horizontal) ? (pt.x - start.x) : (start.y - pt.y)) - dx));
            mxEvent.consume(evt);

            if (initial != getValue()) {
                ignoreClick = true;
                last = null;
            }
        }
    };

    function dropHandler(evt) {
        moveHandler(evt);
        initial = null;
        start = null;
    };

    mxEvent.addGestureListeners(elt, function (evt) {
        start = new mxPoint(mxEvent.getClientX(evt), mxEvent.getClientY(evt));
        initial = getValue();
        ignoreClick = false;
        mxEvent.consume(evt);
    });

    mxEvent.addListener(elt, 'click', mxUtils.bind(this, function (evt) {
        if (!ignoreClick && this.hsplitClickEnabled) {
            var next = (last != null) ? last - dx : 0;
            last = getValue();
            onChange(next);
            mxEvent.consume(evt);
        }
    }));

    mxEvent.addGestureListeners(document, null, moveHandler, dropHandler);

    this.destroyFunctions.push(function () {
        mxEvent.removeGestureListeners(document, null, moveHandler, dropHandler);
    });
};

/**
 * 处理错误响应。
 * 显示错误对话框并处理用户交互。
 *
 * @param {Object} resp - 响应对象或错误对象
 * @param {String} title - 错误窗口标题
 * @param {Function} fn - 点击确定按钮时执行的回调函数
 * @param {Boolean} invokeFnOnClose - 关闭对话框时是否调用fn
 * @param {String} notFoundMessage - 404错误消息
 */
EditorUi.prototype.handleError = function (resp, title, fn, invokeFnOnClose, notFoundMessage) {
    var e = (resp != null && resp.error != null) ? resp.error : resp;

    if (e != null || title != null) {
        var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
        var btn = mxResources.get('ok');
        title = (title != null) ? title : mxResources.get('error');

        if (e != null && e.message != null) {
            msg = mxUtils.htmlEntities(e.message);
        }

        this.showError(title, msg, btn, fn, null, null, null, null, null,
            null, null, null, (invokeFnOnClose) ? fn : null);
    } else if (fn != null) {
        fn();
    }
};

/**
 * 显示错误对话框。
 * 创建和显示自定义的错误消息对话框。
 *
 * @param {String} title - 错误窗口标题
 * @param {String} msg - 错误对话框内容
 * @param {String} btn - 错误对话框确认按钮
 * @param {Function} fn - 接受时执行的函数
 * @param {String} retry - 错误对话框错误按钮
 * @param {String} btn2 - 第二个按钮
 * @param {Function} fn2 - 第二个按钮点击时执行的函数
 * @param {String} btn3 - 第三个按钮
 * @param {Function} fn3 - 第三个按钮点击时执行的函数
 * @param {Number} w - 错误对话框宽度
 * @param {Number} h - 错误对话框高度
 * @param {Boolean} hide - 对话框是否隐藏
 * @param {Function} onClose - 关闭时执行的函数
 */
EditorUi.prototype.showError = function (title, msg, btn, fn, retry, btn2, fn2, btn3, fn3, w, h, hide, onClose) {
    var dlg = new ErrorDialog(this, title, msg, btn || mxResources.get('ok'),
        fn, retry, btn2, fn2, hide, btn3, fn3);
    var lines = Math.ceil((msg != null) ? msg.length / 50 : 1);
    this.showDialog(dlg.container, w || 340, h || (100 + lines * 20), true, false, onClose);
    dlg.init();
};

/**
 * 显示对话框。
 * 创建并显示一个模态或非模态对话框，管理对话框的生命周期和事件处理。
 *
 * @param {Element} elt - 对话框内容元素
 * @param {number} w - 对话框宽度
 * @param {number} h - 对话框高度
 * @param {boolean} modal - 是否为模态对话框
 * @param {boolean} closable - 是否可关闭
 * @param {Function} onClose - 关闭时的回调函数
 * @param {boolean} noScroll - 是否禁用滚动
 * @param {boolean} transparent - 是否透明
 * @param {Function} onResize - 尺寸变化时的回调函数
 * @param {boolean} ignoreBgClick - 是否忽略背景点击
 */
EditorUi.prototype.showDialog = function (elt, w, h, modal, closable, onClose, noScroll, transparent, onResize, ignoreBgClick) {
    this.editor.graph.tooltipHandler.resetTimer();
    this.editor.graph.tooltipHandler.hideTooltip();

    if (this.dialogs == null) {
        this.dialogs = [];
    }

    this.dialog = new Dialog(this, elt, w, h, modal, closable, onClose, noScroll, transparent, onResize, ignoreBgClick);
    this.dialogs.push(this.dialog);
};

/**
 * 隐藏对话框。
 * 从对话框堆栈中移除并关闭指定的对话框。
 *
 * @param {boolean} cancel - 是否取消对话框操作
 * @param {boolean} isEsc - 是否通过ESC键关闭
 * @param {Element} matchContainer - 要匹配的容器元素
 */
/**
 * 隐藏对话框。
 * 关闭当前显示的对话框并清理相关资源。
 *
 * @param {boolean} cancel - 是否为取消操作
 * @param {boolean} isEsc - 是否由ESC键触发
 * @param {Element} matchContainer - 匹配的容器元素
 */
EditorUi.prototype.hideDialog = function (cancel, isEsc, matchContainer) {
    if (this.dialogs != null && this.dialogs.length > 0) {
        if (matchContainer != null && matchContainer != this.dialog.container.firstChild) {
            return;
        }

        var dlg = this.dialogs.pop();

        if (dlg.close(cancel, isEsc) == false) {
            //add the dialog back if dialog closing is cancelled
            this.dialogs.push(dlg);
            return;
        }

        this.dialog = (this.dialogs.length > 0) ? this.dialogs[this.dialogs.length - 1] : null;
        this.editor.fireEvent(new mxEventObject('hideDialog'));

        if (this.dialog == null && this.editor.graph.container.style.visibility != 'hidden') {
            window.setTimeout(mxUtils.bind(this, function () {
                if (this.editor.graph.isEditing() && this.editor.graph.cellEditor.textarea != null) {
                    this.editor.graph.cellEditor.textarea.focus();
                } else {
                    mxUtils.clearSelection();
                    this.editor.graph.container.focus();
                }
            }), 0);
        }
    }
};

/**
 * 处理Ctrl+Enter键盘快捷键来克隆单元格。
 * 在编辑器中处理用于克隆选中单元格的组合键。
 */
EditorUi.prototype.ctrlEnter = function () {
    var graph = this.editor.graph;

    if (graph.isEnabled()) {
        try {
            var cells = graph.getSelectionCells();
            var lookup = new mxDictionary();
            var newCells = [];

            for (var i = 0; i < cells.length; i++) {
                // 克隆表格行而不是单元格
                var cell = (graph.isTableCell(cells[i])) ? graph.model.getParent(cells[i]) : cells[i];

                if (cell != null && !lookup.get(cell)) {
                    lookup.put(cell, true);
                    newCells.push(cell);
                }
            }

            graph.setSelectionCells(graph.duplicateCells(newCells, false));
        } catch (e) {
            this.handleError(e);
        }
    }
};

/**
 * 显示颜色选择对话框。
 * 打开颜色选择器允许用户选择颜色。
 */
EditorUi.prototype.pickColor = function (color, apply) {
    var graph = this.editor.graph;
    var selState = graph.cellEditor.saveSelection();
    var h = 226 + ((Math.ceil(ColorDialog.prototype.presetColors.length / 12) +
        Math.ceil(ColorDialog.prototype.defaultColors.length / 12)) * 17);

    var dlg = new ColorDialog(this, color || 'none', function (color) {
        graph.cellEditor.restoreSelection(selState);
        apply(color);
    }, function () {
        graph.cellEditor.restoreSelection(selState);
    });
    this.showDialog(dlg.container, 230, h, true, false);
    dlg.init();
};

/**
 * 打开文件对话框。
 * 创建打开文件对话框，允许用户选择和加载文件。
 */
/**
 * 打开文件。
 * 打开文件选择对话框允许用户选择并加载文件。
 */
EditorUi.prototype.openFile = function () {
    // 打开后关闭对话框
    window.openFile = new OpenFile(mxUtils.bind(this, function (cancel) {
        this.hideDialog(cancel);
    }));

    // 如果对话框关闭则移除openFile
    this.showDialog(new OpenDialog(this).container, (Editor.useLocalStorage) ? 640 : 320,
        (Editor.useLocalStorage) ? 480 : 220, true, true,
        function () {
            window.openFile = null;
        });
};

/**
 * 从数据传输事件的HTML数据中提取图形模型。
 * 从拖放或粘贴操作的HTML内容中解析出图形数据。
 */
/**
 * 从HTML数据中提取图形模型。
 * 从包含图形数据的HTML内容中解析出图形模型信息。
 *
 * @param {string} data - 包含图形数据的HTML字符串
 * @returns {Object} 提取的图形模型数据
 */
EditorUi.prototype.extractGraphModelFromHtml = function (data) {
    var result = null;

    try {
        var idx = data.indexOf('&lt;mxGraphModel ');

        if (idx >= 0) {
            var idx2 = data.lastIndexOf('&lt;/mxGraphModel&gt;');

            if (idx2 > idx) {
                result = data.substring(idx, idx2 + 21).replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/\\&quot;/g, '"').replace(/\n/g, '');
            }
        }
    } catch (e) {
        // ignore
    }

    return result;
};

/**
 * 在编辑器中打开给定的文件。
 * 处理从事件中提取的文件数据并在编辑器中打开。
 */
/**
 * 从事件中提取图形模型。
 * 从拖放或粘贴事件中提取图形数据。
 *
 * @param {Event} evt - 包含图形数据的事件对象
 * @returns {Object} 提取的图形模型数据
 */
EditorUi.prototype.extractGraphModelFromEvent = function (evt) {
    var result = null;
    var data = null;

    if (evt != null) {
        var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;

        if (provider != null) {
            if (document.documentMode == 10 || document.documentMode == 11) {
                data = provider.getData('Text');
            } else {
                data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;

                if (mxUtils.indexOf(provider.types, 'text/plain' && (data == null || data.length == 0))) {
                    data = provider.getData('text/plain');
                }
            }

            if (data != null) {
                data = Graph.zapGremlins(mxUtils.trim(data));

                // 尝试将数据解析为包含嵌入式XML的HTML文档
                var xml = this.extractGraphModelFromHtml(data);

                if (xml != null) {
                    data = xml;
                }
            }
        }
    }

    if (data != null && this.isCompatibleString(data)) {
        result = data;
    }

    return result;
};

/**
 * 为子类提供的钩子方法，如果事件数据是支持的格式则返回true。
 * 此实现始终返回false。
 */
/**
 * 检查字符串是否为兼容格式。
 * 判断给定的数据字符串是否为编辑器支持的格式。
 *
 * @param {string} data - 要检查的数据字符串
 * @returns {boolean} 如果格式兼容则返回true
 */
EditorUi.prototype.isCompatibleString = function (data) {
    return false;
};

/**
 * 向给定的菜单和父元素添加标签菜单项。
 * 在指定的菜单中添加与标签相关的操作选项。
 */
/**
 * 保存文件。
 * 将当前图形数据保存为文件。
 *
 * @param {boolean} forceDialog - 是否强制显示保存对话框
 */
EditorUi.prototype.saveFile = function (forceDialog) {
    var downLink = document.createElement('a');
    downLink.download = "mxGraphXml.xml";
    downLink.style.display = 'none';
    var blob = new Blob([mxUtils.getXml(this.editor.getGraphXml())]);
    downLink.href = URL.createObjectURL(blob);
    document.body.appendChild(downLink);
    downLink.click();
    document.body.removeChild(downLink);
    // if (!forceDialog && this.editor.filename != null) {
    //     this.save(this.editor.getOrCreateFilename());
    // } else {
    //     var dlg = new FilenameDialog(this, this.editor.getOrCreateFilename(), mxResources.get('save'), mxUtils.bind(this, function (name) {
    //         this.save(name);
    //     }), null, mxUtils.bind(this, function (name) {
    //         if (name != null && name.length > 0) {
    //             return true;
    //         }
    //
    //         mxUtils.confirm(mxResources.get('invalidName'));
    //
    //         return false;
    //     }));
    //     this.showDialog(dlg.container, 300, 100, true, true);
    //     dlg.init();
    // }
};

/**
 * @description 获取关系线的连接状态
 * @param
 */
/**
 * 获取关系状态。
 * 返回当前关系管理的状态信息。
 *
 * @returns {Object} 关系状态对象
 */
EditorUi.prototype.getRelationStatus = function () {
    const cells = this.editor.graph.modal.cells
    const result = []
    for (const key in cells) {
        if (cells.hasOwnProperty(key)) {
            const cell = cells[key];
            if (cell.value instanceof Object && cell.isEdge) {
                const name = cell.value.getAttribute('name')
                if (!cell.source) {
                    result.push({
                        cell,
                        message: `关系线 ${name} 没有连接源节点`
                    })
                } else if (!cell.target) {
                    result.push({
                        cell,
                        message: `关系线 ${name} 没有连接目标节点`
                    })
                }
            }
        }
    }

    result.forEach(item => {

    })


    return !!result.length
};

/**
 * 保存当前图形。
 * 检查图形是否为空，如果为空则提示用户确认，否则直接保存。
 *
 * @param {string} name - 保存的文件名
 * @returns {Promise} 保存操作的Promise对象
 */
/**
 * 保存操作。
 * 执行保存操作，将图形数据保存到指定名称的位置。
 *
 * @param {string} name - 保存的文件名称
 */
EditorUi.prototype.save = function (name) {
    console.log("save");
    var xml = mxUtils.getXml(this.editor.getGraphXml());
    const objectNode = mxUtils.parseXml(xml).documentElement;
    const graphSize = Array.prototype.slice.call(objectNode.lastElementChild.children).filter(item => !!item.innerHTML).length
    if (graphSize === 1) {
        return window.parent.$MessageBox
            .confirm('当前保存图形为空，是否继续保存？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
            .then(() => this.saveGraph(name));
    } else {
        return this.saveGraph(name);
    }
};

/**
 * 将树形结构转换为列表。
 * 将层次化的树形数据结构展平为一维列表。
 *
 * @param {Object} treeData - 树形数据
 * @param {string} field - 子节点字段名，默认为'children'
 * @returns {Array} 展平后的列表
 */
EditorUi.prototype.treeToList = function (treeData, field = 'children') {
    const result = [];
    treeData.forEach(item => {
        flatten(item)
    })

    function flatten(node) {
        result.push(node)
        if (node[field] && node[field].length) {
            node[field].forEach(child => {
                flatten(child)
            })
        }
    }

    return result
}

/**
 * 获取XML数据的大小。
 * 计算XML字符串的字节大小。
 *
 * @param {string} xml - XML字符串
 * @returns {number} XML数据的字节大小
 */
EditorUi.prototype.getXmlSize = function (xml) {
    return new Blob([xml]).size / (1024 * 1024)
}

/**
 * 异步保存图形到服务器。
 * 执行完整的图形保存流程，包括数据验证、格式转换和服务器通信。
 *
 * @param {string} name - 保存的文件名
 * @param {boolean} updateTreeNode - 是否更新树节点，默认为true
 * @returns {Promise} 保存操作的Promise对象
 */
/**
 * 异步保存图形。
 * 异步执行图形保存操作，支持更新树节点。
 *
 * @param {string} name - 保存的图形名称
 * @param {boolean} updateTreeNode - 是否更新树节点，默认为true
 * @returns {Promise} 保存操作的Promise对象
 */
EditorUi.prototype.saveGraph = async function (name, updateTreeNode = true) {
    let ele = document.getElementById('geDiagramContainer');
    let scrollLeft = ele.scrollLeft;
    let scrollTop = ele.scrollTop;
    let w, h;
    if (name != null) {
        drawioBus.$emit('beforeSaveGraph', window)

        if (this.editor.graph.isEditing()) {
            this.editor.graph.stopEditing();
        }

        const getDefaultParentCells = myEditor.editor.graph.getDefaultParent() ? myEditor.editor.graph.getDefaultParent().children : null;
        if (getDefaultParentCells) {
            const cells = this.treeToList(getDefaultParentCells);
            $.each(cells, function (index, currentCell) {
                if (currentCell.getValue() != null && typeof (currentCell.getValue()) == 'object' && currentCell.getAttribute('business') === 'BUSINESS_ER_ATTRIBUTE') {
                    if (!currentCell.id) {
                        currentCell.id = index.toString() + Date.now() + (Math.floor(Math.random() * 10000)).toString()
                    }
                }
            });
        }

        //页面xml
        var xml = mxUtils.getXml(this.editor.getGraphXml());
        if (this.getXmlSize(xml) > 4) {
            window.parent.$Message({
                message: '请控制画布内容大小不要超过4M！',
                type: 'warning'
            });
            return
        }
        //图片xml
        var imgExport = new mxImageExport();
        var scale = 1;
        var b = 1;
        var bounds = this.editor.graph.getGraphBounds();
        var vs = this.editor.graph.view.scale;

        // 新的图片导出功能
        var xmlDoc = mxUtils.createXmlDocument();
        var root = xmlDoc.createElement('output');
        xmlDoc.appendChild(root);

        // 渲染图形。偏移量在绘制状态时会与状态缩放相乘。
        var xmlCanvas = new mxXmlCanvas2D(root);
        xmlCanvas.translate(Math.floor((b / scale - bounds.x) / vs), Math.floor((b / scale - bounds.y) / vs));
        xmlCanvas.scale(scale / vs);
        imgExport.drawState(this.editor.graph.getView().getState(this.editor.graph.model.root), xmlCanvas);

        // 整理请求数据
        w = Math.ceil(bounds.width * scale / vs + 2 * b);
        h = Math.ceil(bounds.height * scale / vs + 2 * b);
        // 创建遮罩层
        const loading = window.parent.$Loading.service({
            lock: true,
            text: '保存中......',
            spinner: 'el-icon-loading',
        })

        var svgXml = await myEditor.transToSvg(1.5, false, true, false, true, false, "1", true, false, "auto", null, "diagram")
        var pngXml = await myEditor.transToImage(1.5, false, true, false, true, "1", true, false, null, false, null, null, "diagram")

        // console.log('-----xml------',xml)
        // console.log('-----pngXml------',pngXml)
        var children = this.editor.graph.getDefaultParent().children;
        if (children != null && (children.length = 0)) {
            svgXml = '';
            pngXml = '';
        }
        try {
            const params = {
                'dataXml': encodeURIComponent(xml),
                'modelId': modelId,
                'svgXml': encodeURIComponent(svgXml),
                'pngXml': encodeURIComponent(pngXml),
                'width': w,
                'height': h,
                'bgUrl': bgUrl
            }
            if (window.zTreeObj && 'mind_map' === window.zTreeObj.currentSelectedNode ? .type)(params.type = 'mind_map');

            if (window.isGuideModel) {
                params.frameWorkCode = window.frameworkCode;
                params.modelId = window.guideModelId;
            }
            const data = await window.$axios.post(SAVE_URL, params)
            // removeSaveLoading(); // 删除遮罩层
            const preveGraphScale = window.myEditor.editor.graph.view.getScale();
            const prevOutlineWindow = myEditor.actions.outlineWindow
            const outlineWindowData = prevOutlineWindow && prevOutlineWindow.window && {
                selected: myEditor.actions.get('outline').isSelected(),
                x: prevOutlineWindow.window.getX(),
                y: prevOutlineWindow.window.getY(),
                width: prevOutlineWindow.window.div.clientWidth,
                height: prevOutlineWindow.window.div.clientHeight,
            }
            const prevLayersWindow = myEditor.actions.layersWindow
            const layersWindowData = prevLayersWindow && prevLayersWindow.window && {
                selected: myEditor.actions.get('layers').isSelected(),
                x: prevLayersWindow.window.getX(),
                y: prevLayersWindow.window.getY(),
                width: prevLayersWindow.window.div.clientWidth,
                height: prevLayersWindow.window.div.clientHeight,
            }
            this.destroy();
            window.myEditor = new EditorUi(new Editor(
                urlParams['chrome'] == '0' || uiTheme == 'min',
                null, null, null, urlParams['chrome'] != '0'));

            drawioBus.$emit('reRegistryEditorUi', window);

            if (outlineWindowData && outlineWindowData.selected) {
                myEditor.actions.get('outline').funct()
                const outlineWindow = myEditor.actions.outlineWindow
                if (outlineWindow) {
                    outlineWindow.window.setLocation(outlineWindowData.x, outlineWindowData.y)
                    outlineWindow.window.setSize(outlineWindowData.width, outlineWindowData.height)
                }
            }
            if (layersWindowData && layersWindowData.selected) {
                myEditor.actions.get('layers').funct()
                const layersWindow = myEditor.actions.layersWindow
                if (layersWindow) {
                    layersWindow.window.setLocation(layersWindowData.x, layersWindowData.y)
                    layersWindow.window.setSize(layersWindowData.width, layersWindowData.height)
                }
            }
            if (data.code === 200) {
                if (!updateTreeNode) return
                var data_xml = myEditor.editor.graph.zapGremlins(mxUtils.trim(data.data.xml));
                window.myEditor.editor.setGraphXml(mxUtils.parseXml(data_xml).documentElement);
                //设置背景图
                if (data.data.bgUrl != null && data.data.bgUrl.length > 0) {
                    bgUrl = data.data.bgUrl;
                    var img = new Image();
                    img.onload = function () {
                        myEditor.editor.graph.refresh();
                    }
                    var src = window.location.protocol + "//" + window.location.host + PICTURE_PATH + "?id=" + data.data.bgUrl;
                    img.src = src;
                    myEditor.setBackgroundImage(img);
                    console.log("bgUrl", src);
                }
                window.myEditor.editor.graph.zoom(preveGraphScale);
                myEditor.editor.undoManager.clear();

                myEditor.editor.setModified(false)

                window.isPokePatttern = false
                window.myEditor.graphEvent.exitAddPattern()

                setTimeout(() => {
                    // 清空number
                    window.numberProxy.maxBigNum = {}
                    window.numberProxy.maxSuffixCodeNum = {}
                    drawioBus.$emit('dataCheckListRefresh') // 刷新数据检查列表
                    drawioBus.$emit('afterSaveGraph')
                    // 更新tree
                    if (window.sidebarStructure) {
                        window.sidebarStructure.updateTreeNode();
                        window.sidebarStructure.updateGraphListener();
                    }
                    // 更新数据定义
                    window.sidebarScan && window.sidebarScan.refreshData();
                    modelType === 'DIAGRAM_SYSML_SEQUENCE' && myEditor.toolbar && myEditor.toolbar.setUmlPageMenu();

                    let ele = document.getElementById('geDiagramContainer');
                    if (ele) {
                        ele.scrollTo({
                            top: scrollTop,
                            left: scrollLeft,
                        });
                        let offset = {
                            scrollTop: scrollTop,
                            scrollLeft: scrollLeft,
                        }
                        localStorage.setItem('offset', JSON.stringify(offset))
                    }
                })
                mianCallBack(window.myEditor)
                window.parent.$Message({
                    message: '保存成功',
                    type: 'success'
                })
            } else {
                var data_xml = myEditor.editor.graph.zapGremlins(mxUtils.trim(xml));
                window.myEditor.editor.setGraphXml(mxUtils.parseXml(data_xml).documentElement);
                if (data.code === 305) {
                    console.log(data.data)
                    const pageIdList = data.data.pageIdList;
                    pageIdList.forEach(cellId => {
                        const graph = window.myEditor.editor.graph;
                        console.log(graph.getModel().getCell(cellId))
                        const cell = graph.getModel().getCell(cellId);
                        if (cell) {
                            window.myEditor.editor.graph.setCellStyles(mxConstants.STYLE_STROKEWIDTH, "5", [cell]);
                            window.myEditor.editor.graph.setCellStyles(mxConstants.STYLE_STROKECOLOR, "#ff0000", [cell]);
                        }
                    })
                } else {
                    console.log('保存失败', data);
                    const getDefaultParentCells = myEditor.editor.graph.getDefaultParent() ? myEditor.editor.graph.getDefaultParent().children : null;
                    if (getDefaultParentCells && !(window.zTreeObj && window.zTreeObj.currentSelectedNode.modelType === 'DIAGRAM_IDEF0')) {
                        const edgeCells = this.treeToList(getDefaultParentCells).filter(i => i.isEdge() && i.value instanceof Object);
                        let notConnectEdge = [];
                        $.each(edgeCells, function (index, currentCell) {
                            if (currentCell.style && currentCell.style.includes('endArrow=')) {
                                if (!currentCell.source || !currentCell.target) {
                                    currentCell.notConnect = true;
                                    window.myEditor.editor.graph.setCellStyles(mxConstants.STYLE_STROKEWIDTH, "5", [currentCell]);
                                    window.myEditor.editor.graph.setCellStyles(mxConstants.STYLE_STROKECOLOR, "#ff0000", [currentCell]);
                                    notConnectEdge.push(currentCell);
                                }
                            }
                        });
                        if (notConnectEdge.length) {
                            const graph = window.myEditor.editor.graph;
                            const edge = notConnectEdge[0];
                            graph.scrollCellToVisible(edge)
                        }
                    }
                }
                myEditor.editor.undoManager.clear();
                // window.top.$Message({
                //     message: '保存失敗',
                //     type: 'error'
                // })
            }
        } catch (e) {
            console.log(e);
        } finally {
            loading.close()
        }
    }
};

/**
 * 将时间序列转换为状态。
 * 异步将时间序列数据转换为状态数据。
 *
 * @param {string} name - 转换的名称
 * @returns {Promise} 转换操作的Promise对象
 */
EditorUi.prototype.timeSequenceToState = async function (name) {

    var res = confirm("是否确定生成？");
    if (res) {
        if (name != null) {
            //页面xml
            var xml = mxUtils.getXml(this.editor.getGraphXml());
            createSaveLoading(); // 创建遮罩层
            try {
                window.$axios.post(TimeSequenceToState, {
                    data: {
                        // 'dataXml': encodeURIComponent(xml),
                        'modelId': modelId,
                        'bgUrl': bgUrl
                    },
                }).then((data) => {
                    myEditor.destroy();
                    window.myEditor = new EditorUi(new Editor(
                        urlParams['chrome'] == '0' || uiTheme == 'min',
                        null, null, null, urlParams['chrome'] != '0'));
                    if (data.statusCode == 200) {
                        /*                            var data_xml = myEditor.editor.graph.zapGremlins(mxUtils.trim(data.data.xml));
                                                window.myEditor.editor.setGraphXml(mxUtils.parseXml(data_xml).documentElement);
                                                //设置背景图
                                                if (data.data.bgUrl != null && data.data.bgUrl.length > 0) {
                                                    bgUrl = data.data.bgUrl;
                                                    var img = new Image();
                                                    img.onload = function () {
                                                        myEditor.editor.graph.refresh();
                                                    }
                                                    var src = window.location.protocol + "//" + window.location.host + PICTURE_PATH + "?id=" + data.data.bgUrl;
                                                    img.src = src;
                                                    myEditor.setBackgroundImage(img);
                                                    console.log("bgUrl", src);
                                                }*/
                        if (window.parent.messageDialog) {
                            window.parent.messageDialog('保存成功!');
                        } else {
                            alert('保存成功!');
                        }

                        //成功后刷新树
                        window.parent.refreshStateDiagramTree();
                    } else {
                        /*                            var data_xml = myEditor.editor.graph.zapGremlins(mxUtils.trim(xml));
                                                window.myEditor.editor.setGraphXml(mxUtils.parseXml(data_xml).documentElement);*/
                        window.parent.alertDialog(data.message);
                    }
                    removeSaveLoading(); // 删除遮罩层
                }).catch(e => {

                })
            } catch (e) {
                console.log(e);
            }
        }
    }

};
/**
 * 执行给定的布局。
 * 运行指定的布局算法来重新排列图形元素。
 */
/**
 * 执行布局算法。
 * 运行指定的布局算法来重新排列图形元素。
 *
 * @param {Function} exec - 要执行的布局函数
 * @param {boolean} animate - 是否使用动画
 * @param {Function} post - 布局完成后的回调函数
 */
EditorUi.prototype.executeLayout = function (exec, animate, post) {
    var graph = this.editor.graph;

    if (graph.isEnabled()) {
        graph.getModel().beginUpdate();
        try {
            exec();
        } catch (e) {
            throw e;
        } finally {
            // 对图形模型中的更改进行动画处理，除了
            // Camino浏览器，因为动画速度太慢
            if (this.allowAnimation && animate && (navigator.userAgent == null ||
                    navigator.userAgent.indexOf('Camino') < 0)) {
                // 用于异步动画图形布局结果的新API
                var morph = new mxMorphing(graph);
                morph.addListener(mxEvent.DONE, mxUtils.bind(this, function () {
                    graph.getModel().endUpdate();

                    if (post != null) {
                        post();
                    }
                }));

                morph.startAnimation();
            } else {
                graph.getModel().endUpdate();

                if (post != null) {
                    post();
                }
            }
        }
    }
};

/**
 * 显示图像对话框。
 * 打开图像选择和配置对话框，允许用户插入或编辑图像。
 *
 * @param {String} title - 对话框标题
 * @param {String} value - 当前图像值
 * @param {Function} fn - 回调函数
 * @param {Boolean} ignoreExisting - 是否忽略现有图像
 */
/**
 * 显示图像对话框。
 * 打开图像选择和配置对话框，允许用户插入或编辑图像。
 *
 * @param {String} title - 对话框标题
 * @param {String} value - 当前图像值
 * @param {Function} fn - 回调函数
 * @param {Boolean} ignoreExisting - 是否忽略现有图像
 */
EditorUi.prototype.showImageDialog = function (title, value, fn, ignoreExisting) {
    var cellEditor = this.editor.graph.cellEditor;
    var selState = cellEditor.saveSelection();
    var newValue = mxUtils.prompt(title, value);
    cellEditor.restoreSelection(selState);

    if (newValue != null && newValue.length > 0) {
        var img = new Image();

        img.onload = function () {
            fn(newValue, img.width, img.height);
        };
        img.onerror = function () {
            fn(null);
            mxUtils.alert(mxResources.get('fileNotFound'));
        };

        img.src = newValue;
    } else {
        fn(null);
    }
};

/**
 * 显示链接对话框。
 * 打开链接编辑对话框，允许用户输入或编辑链接。
 *
 * @param {String} value - 当前链接值
 * @param {String} btnLabel - 按钮标签
 * @param {Function} fn - 回调函数
 */
/**
 * 显示链接对话框。
 * 打开链接编辑对话框，允许用户输入或编辑链接。
 *
 * @param {String} value - 当前链接值
 * @param {String} btnLabel - 按钮标签
 * @param {Function} fn - 回调函数
 */
EditorUi.prototype.showLinkDialog = function (value, btnLabel, fn) {
    var dlg = new LinkDialog(this, value, btnLabel, fn);
    this.showDialog(dlg.container, 420, 90, true, true);
    dlg.init();
};

/**
 * 显示数据对话框。
 * 打开元数据编辑对话框，允许用户编辑单元格的元数据。
 *
 * @param {mxCell} cell - 要编辑的单元格
 */
/**
 * 显示数据对话框。
 * 打开元数据编辑对话框，允许用户编辑单元格的元数据。
 *
 * @param {mxCell} cell - 要编辑的单元格
 */
EditorUi.prototype.showDataDialog = function (cell) {
    if (cell != null) {
        var dlg = new EditDataDialog(this, cell);
        this.showDialog(dlg.container, 480, 420, true, false, null, false);
        dlg.init();
    }
};

/**
 * 显示背景图像对话框。
 * 打开背景图像设置对话框，允许用户配置图形背景图像。
 *
 * @param {Function} apply - 应用函数
 * @param {Object} img - 当前图像对象
 */
/**
 * 显示背景图像对话框。
 * 打开背景图像设置对话框，允许用户配置图形背景图像。
 *
 * @param {Function} apply - 应用函数
 * @param {Object} img - 当前图像对象
 */
EditorUi.prototype.showBackgroundImageDialog = function (apply, img) {
    apply = (apply != null) ? apply : mxUtils.bind(this, function (image) {
        var change = new ChangePageSetup(this, null, image);
        change.ignoreColor = true;

        this.editor.graph.model.execute(change);
    });

    var newValue = mxUtils.prompt(mxResources.get('backgroundImage'), (img != null) ? img.src : '');

    if (newValue != null && newValue.length > 0) {
        var img = new Image();

        img.onload = function () {
            apply(new mxImage(newValue, img.width, img.height), false);
        };
        img.onerror = function () {
            apply(null, true);
            mxUtils.alert(mxResources.get('fileNotFound'));
        };

        img.src = newValue;
    } else {
        apply(null);
    }
};

/**
 * 设置背景图像。
 * 为图形设置背景图像并更新相关显示。
 */
/**
 * 设置背景图像。
 * 为图形设置背景图像并更新相关显示。
 *
 * @param {Object} image - 背景图像对象
 */
EditorUi.prototype.setBackgroundImage = function (image) {
    this.editor.graph.setBackgroundImage(image);
    this.editor.graph.view.validateBackgroundImage();

    this.fireEvent(new mxEventObject('backgroundImageChanged'));
};

/**
 * 显示确认对话框。
 * 显示确认消息并根据用户选择执行相应的回调函数。
 *
 * @param {String} msg - 确认消息
 * @param {Function} okFn - 确认时执行的函数
 * @param {Function} cancelFn - 取消时执行的函数
 */
/**
 * 显示确认对话框。
 * 显示确认消息并根据用户选择执行相应的回调函数。
 *
 * @param {String} msg - 确认消息
 * @param {Function} okFn - 确认时执行的函数
 * @param {Function} cancelFn - 取消时执行的函数
 */
EditorUi.prototype.confirm = function (msg, okFn, cancelFn) {
    if (mxUtils.confirm(msg)) {
        if (okFn != null) {
            okFn();
        }
    } else if (cancelFn != null) {
        cancelFn();
    }
};

/**
 * 创建概览窗口。
 * 为指定窗口创建图形概览组件，显示整个图形的缩略图。
 *
 * @param {mxWindow} wnd - 概览窗口对象
 * @returns {mxOutline} 创建的概览组件
 */
EditorUi.prototype.createOutline = function (wnd) {
    var outline = new mxOutline(this.editor.graph);
    outline.border = 20;

    mxEvent.addListener(window, 'resize', function () {
        outline.update();
    });

    this.addListener('pageFormatChanged', function () {
        outline.update();
    });

    return outline;
};

// Alt+Shift+Keycode mapping to action
/**
 * Alt+Shift组合键操作映射。
 * 定义Alt+Shift组合键对应的操作名称。
 */
EditorUi.prototype.altShiftActions = {
    67: 'clearWaypoints', // Alt+Shift+C
    65: 'connectionArrows', // Alt+Shift+A
    76: 'editLink', // Alt+Shift+L
    80: 'connectionPoints', // Alt+Shift+P
    84: 'editTooltip', // Alt+Shift+T
    86: 'pasteSize', // Alt+Shift+V
    88: 'copySize' // Alt+Shift+X
};

/**
 * 为当前图形和历史记录创建键盘事件处理程序。
 * 初始化键盘快捷键和输入事件的处理逻辑。
 *
 * @param {Editor} editor - 编辑器实例
 * @returns {mxKeyHandler} 创建的键盘处理程序
 */
EditorUi.prototype.createKeyHandler = function (editor) {
    var editorUi = this;
    var graph = this.editor.graph;
    var keyHandler = new mxKeyHandler(graph);

    var isEventIgnored = keyHandler.isEventIgnored;
    keyHandler.isEventIgnored = function (evt) {
        // 通过动作处理撤销/重做/ctrl+./,/u，并允许ctrl+b/i
        // only if editing value is HTML (except for FF and Safari)
        return !(mxEvent.isShiftDown(evt) && evt.keyCode == 9) &&
            ((!this.isControlDown(evt) || mxEvent.isShiftDown(evt) ||
                (evt.keyCode != 90 && evt.keyCode != 89 && evt.keyCode != 188 &&
                    evt.keyCode != 190 && evt.keyCode != 85)) && ((evt.keyCode != 66 && evt.keyCode != 73) ||
                !this.isControlDown(evt) || (this.graph.cellEditor.isContentEditing() &&
                    !mxClient.IS_FF && !mxClient.IS_SF)) && isEventIgnored.apply(this, arguments));
    };

    // 忽略图形启用状态但不忽略无边框状态
    keyHandler.isEnabledForEvent = function (evt) {
        return (!mxEvent.isConsumed(evt) && this.isGraphEvent(evt) && this.isEnabled() &&
            (editorUi.dialogs == null || editorUi.dialogs.length == 0));
    };

    // 在Mac上将command键路由到control键
    keyHandler.isControlDown = function (evt) {
        return mxEvent.isControlDown(evt) || (mxClient.IS_MAC && evt.metaKey);
    };

    // 键盘操作队列，用于延迟执行键盘操作
    var queue = [];
    // 键盘操作线程，用于管理异步键盘操作
    var thread = null;

    // 使用光标键移动单元格的辅助函数
    /**
     * 使用键盘移动或调整单元格大小的内部函数。
     * @param {number} keyCode - 键盘按键代码
     * @param {number} stepSize - 移动或调整的步长
     * @param {boolean} resize - 是否调整大小而不是移动
     */
    function nudge(keyCode, stepSize, resize) {
        queue.push(function () {
            if (!graph.isSelectionEmpty() && graph.isEnabled()) {
                stepSize = (stepSize != null) ? stepSize : 1;

                if (resize) {
                    // 调整所有选定顶点的大小
                    graph.getModel().beginUpdate();
                    try {
                        var cells = graph.getSelectionCells();

                        for (var i = 0; i < cells.length; i++) {
                            if (graph.getModel().isVertex(cells[i]) && graph.isCellResizable(cells[i])) {
                                var geo = graph.getCellGeometry(cells[i]);

                                if (geo != null) {
                                    geo = geo.clone();

                                    if (keyCode == 37) {
                                        geo.width = Math.max(0, geo.width - stepSize);
                                    } else if (keyCode == 38) {
                                        geo.height = Math.max(0, geo.height - stepSize);
                                    } else if (keyCode == 39) {
                                        geo.width += stepSize;
                                    } else if (keyCode == 40) {
                                        geo.height += stepSize;
                                    }

                                    graph.getModel().setGeometry(cells[i], geo);
                                }
                            }
                        }
                    } finally {
                        graph.getModel().endUpdate();
                    }
                } else {
                    // 在堆栈布局中向上/向下移动顶点
                    var cell = graph.getSelectionCell();
                    var parent = graph.model.getParent(cell);
                    var layout = null;

                    if (graph.getSelectionCount() == 1 && graph.model.isVertex(cell) &&
                        graph.layoutManager != null && !graph.isCellLocked(cell)) {
                        layout = graph.layoutManager.getLayout(parent);
                    }

                    if (layout != null && layout.constructor == mxStackLayout) {
                        var index = parent.getIndex(cell);

                        if (keyCode == 37 || keyCode == 38) {
                            graph.model.add(parent, cell, Math.max(0, index - 1));
                        } else if (keyCode == 39 || keyCode == 40) {
                            graph.model.add(parent, cell, Math.min(graph.model.getChildCount(parent), index + 1));
                        }
                    } else {
                        var cells = graph.getMovableCells(graph.getSelectionCells());
                        var realCells = [];

                        for (var i = 0; i < cells.length; i++) {
                            // TODO: Use getCompositeParent
                            var style = graph.getCurrentCellStyle(cells[i]);

                            if (mxUtils.getValue(style, 'part', '0') == '1') {
                                var parent = graph.model.getParent(cells[i]);

                                if (graph.model.isVertex(parent) && mxUtils.indexOf(cells, parent) < 0) {
                                    realCells.push(parent);
                                }
                            } else {
                                realCells.push(cells[i]);
                            }
                        }

                        if (realCells.length > 0) {
                            cells = realCells;
                            var dx = 0;
                            var dy = 0;

                            if (keyCode == 37) {
                                dx = -stepSize;
                            } else if (keyCode == 38) {
                                dy = -stepSize;
                            } else if (keyCode == 39) {
                                dx = stepSize;
                            } else if (keyCode == 40) {
                                dy = stepSize;
                            }

                            graph.moveCells(cells, dx, dy);
                        }
                    }
                }
            }
        });

        if (thread != null) {
            window.clearTimeout(thread);
        }

        thread = window.setTimeout(function () {
            if (queue.length > 0) {
                graph.getModel().beginUpdate();

                try {
                    for (var i = 0; i < queue.length; i++) {
                        queue[i]();
                    }

                    queue = [];
                } finally {
                    graph.getModel().endUpdate();
                }
            }
        }, 200);
    };

    // 重写以处理特殊的alt+shift+光标键盘快捷键
    var directions = {
        37: mxConstants.DIRECTION_WEST,
        38: mxConstants.DIRECTION_NORTH,
        39: mxConstants.DIRECTION_EAST,
        40: mxConstants.DIRECTION_SOUTH
    };

    var keyHandlerGetFunction = keyHandler.getFunction;

    mxKeyHandler.prototype.getFunction = function (evt) {
        if (graph.isEnabled()) {
            // TODO: Add alt modified state in core API, here are some specific cases
            if (mxEvent.isShiftDown(evt) && mxEvent.isAltDown(evt)) {
                var action = editorUi.actions.get(editorUi.altShiftActions[evt.keyCode]);

                if (action != null) {
                    return action.funct;
                }
            }

            if (evt.keyCode == 9 && mxEvent.isAltDown(evt)) {
                if (graph.cellEditor.isContentEditing()) {
                    // Alt+Shift+Tab while editing
                    return function () {
                        document.execCommand('outdent', false, null);
                    };
                } else if (mxEvent.isShiftDown(evt)) {
                    // Alt+Shift+Tab
                    return function () {
                        graph.selectParentCell();
                    };
                } else {
                    // Alt+Tab
                    return function () {
                        graph.selectChildCell();
                    };
                }
            } else if (directions[evt.keyCode] != null && !graph.isSelectionEmpty()) {
                // 在macOS上，Control+光标被Expose使用，所以允许Alt+Control来调整大小
                if (!this.isControlDown(evt) && mxEvent.isShiftDown(evt) && mxEvent.isAltDown(evt)) {
                    if (graph.model.isVertex(graph.getSelectionCell())) {
                        return function () {
                            var cells = graph.connectVertex(graph.getSelectionCell(), directions[evt.keyCode],
                                graph.defaultEdgeLength, evt, true);

                            if (cells != null && cells.length > 0) {
                                if (cells.length == 1 && graph.model.isEdge(cells[0])) {
                                    graph.setSelectionCell(graph.model.getTerminal(cells[0], false));
                                } else {
                                    graph.setSelectionCell(cells[cells.length - 1]);
                                }

                                graph.scrollCellToVisible(graph.getSelectionCell());

                                if (editorUi.hoverIcons != null) {
                                    editorUi.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
                                }
                            }
                        };
                    }
                } else {
                    // 通过在下面返回null来避免在未选择顶点时消耗事件
                    // 光标键移动和调整(ctrl)单元格大小
                    if (this.isControlDown(evt)) {
                        return function () {
                            nudge(evt.keyCode, (mxEvent.isShiftDown(evt)) ? graph.gridSize : null, true);
                        };
                    } else {
                        return function () {
                            nudge(evt.keyCode, (mxEvent.isShiftDown(evt)) ? graph.gridSize : null);
                        };
                    }
                }
            }
        }

        return keyHandlerGetFunction.apply(this, arguments);
    };

    // Binds keystrokes to actions
    keyHandler.bindAction = mxUtils.bind(this, function (code, control, key, shift) {
        var action = this.actions.get(key);

        if (action != null) {
            var f = function () {
                if (action.isEnabled()) {
                    action.funct();
                }
            };

            if (control) {
                if (shift) {
                    keyHandler.bindControlShiftKey(code, f);
                } else {
                    keyHandler.bindControlKey(code, f);
                }
            } else {
                if (shift) {
                    keyHandler.bindShiftKey(code, f);
                } else {
                    keyHandler.bindKey(code, f);
                }
            }
        }
    });

    var ui = this;
    var keyHandlerEscape = keyHandler.escape;
    keyHandler.escape = function (evt) {
        window.myEditor.graphEvent.exitAddPattern()
        keyHandlerEscape.apply(this, arguments);
    };

    // Ignores enter keystroke. Remove this line if you want the
    // enter keystroke to stop editing. N, W, T are reserved.
    keyHandler.enter = function () {};

    keyHandler.bindControlShiftKey(36, function () {
        graph.exitGroup();
    }); // Ctrl+Shift+Home
    keyHandler.bindControlShiftKey(35, function () {
        graph.enterGroup();
    }); // Ctrl+Shift+End
    keyHandler.bindShiftKey(36, function () {
        graph.home();
    }); // Ctrl+Shift+Home
    keyHandler.bindKey(35, function () {
        graph.refresh();
    }); // End
    keyHandler.bindAction(107, true, 'zoomIn'); // Ctrl+Plus
    keyHandler.bindAction(109, true, 'zoomOut'); // Ctrl+Minus
    keyHandler.bindAction(80, true, 'print'); // Ctrl+P
    keyHandler.bindAction(79, true, 'outline', true); // Ctrl+Shift+O

    if (!this.editor.chromeless || this.editor.editable) {
        keyHandler.bindControlKey(36, function () {
            if (graph.isEnabled()) {
                graph.foldCells(true);
            }
        }); // Ctrl+Home
        keyHandler.bindControlKey(35, function () {
            if (graph.isEnabled()) {
                graph.foldCells(false);
            }
        }); // Ctrl+End
        keyHandler.bindControlKey(13, function () {
            ui.ctrlEnter();
        }); // Ctrl+Enter
        keyHandler.bindAction(8, false, 'delete'); // Backspace
        keyHandler.bindAction(8, true, 'deleteAll'); // Ctrl+Backspace
        keyHandler.bindAction(8, false, 'deleteLabels', true); // Shift+Backspace
        keyHandler.bindAction(46, false, 'delete'); // Delete
        keyHandler.bindAction(46, true, 'deleteAll'); // Ctrl+Delete
        keyHandler.bindAction(46, false, 'deleteLabels', true); // Shift+Delete
        keyHandler.bindAction(36, false, 'resetView'); // Home
        keyHandler.bindAction(72, true, 'fitWindow', true); // Ctrl+Shift+H
        keyHandler.bindAction(74, true, 'fitPage'); // Ctrl+J
        keyHandler.bindAction(74, true, 'fitTwoPages', true); // Ctrl+Shift+J
        keyHandler.bindAction(48, true, 'customZoom'); // Ctrl+0
        keyHandler.bindAction(82, true, 'turn'); // Ctrl+R
        keyHandler.bindAction(82, true, 'clearDefaultStyle', true); // Ctrl+Shift+R
        keyHandler.bindAction(83, true, 'save'); // Ctrl+S
        keyHandler.bindAction(83, true, 'saveAs', true); // Ctrl+Shift+S
        keyHandler.bindAction(65, true, 'selectAll'); // Ctrl+A
        keyHandler.bindAction(65, true, 'selectNone', true); // Ctrl+A
        keyHandler.bindAction(73, true, 'selectVertices', true); // Ctrl+Shift+I
        keyHandler.bindAction(69, true, 'selectEdges', true); // Ctrl+Shift+E
        keyHandler.bindAction(69, true, 'editStyle'); // Ctrl+E
        keyHandler.bindAction(66, true, 'bold'); // Ctrl+B
        keyHandler.bindAction(66, true, 'toBack', true); // Ctrl+Shift+B
        keyHandler.bindAction(70, true, 'toFront', true); // Ctrl+Shift+F
        // keyHandler.bindAction(68, true, 'duplicate'); // Ctrl+D
        // keyHandler.bindAction(68, true, 'deleteFromModel'); // Ctrl+D
        keyHandler.bindAction(68, true, 'setAsDefaultStyle', true); // Ctrl+Shift+D
        keyHandler.bindAction(90, true, 'undo'); // Ctrl+Z
        keyHandler.bindAction(89, true, 'autosize', true); // Ctrl+Shift+Y
        keyHandler.bindAction(88, true, 'cut'); // Ctrl+X
        keyHandler.bindAction(67, true, 'copy'); // Ctrl+C
        keyHandler.bindAction(86, true, 'paste'); // Ctrl+V
        keyHandler.bindAction(71, true, 'group'); // Ctrl+G
        keyHandler.bindAction(77, true, 'editData'); // Ctrl+M
        keyHandler.bindAction(71, true, 'grid', true); // Ctrl+Shift+G
        keyHandler.bindAction(73, true, 'italic'); // Ctrl+I
        keyHandler.bindAction(76, true, 'lockUnlock'); // Ctrl+L
        keyHandler.bindAction(76, true, 'layers', true); // Ctrl+Shift+L
        keyHandler.bindAction(80, true, 'formatPanel', true); // Ctrl+Shift+P
        keyHandler.bindAction(85, true, 'underline'); // Ctrl+U
        keyHandler.bindAction(85, true, 'ungroup', true); // Ctrl+Shift+U
        keyHandler.bindAction(190, true, 'superscript'); // Ctrl+.
        keyHandler.bindAction(188, true, 'subscript'); // Ctrl+,
        keyHandler.bindAction(9, false, 'indent', true); // Shift+Tab,
        keyHandler.bindKey(13, function () {
            if (graph.isEnabled()) {
                // graph.startEditingAtCell();
            }
        }); // Enter
        keyHandler.bindKey(113, function () {
            if (graph.isEnabled()) {
                graph.customEditCell = new CustomEditCell(graph)
                // graph.startEditingAtCell();
            }
        }); // F2
    }

    if (!mxClient.IS_WIN) {
        keyHandler.bindAction(90, true, 'redo', true); // Ctrl+Shift+Z
    } else {
        keyHandler.bindAction(89, true, 'redo'); // Ctrl+Y
    }

    return keyHandler;
};

/**
 * 销毁编辑器UI实例。
 * 清理所有相关资源、事件监听器和DOM元素，释放内存。
 */
/**
 * 销毁编辑器UI。
 * 清理所有资源、事件监听器和组件，释放内存。
 */
EditorUi.prototype.destroy = function () {
    if (this.actions.outlineWindow) {
        this.actions.outlineWindow.destroy()
        this.actions.outlineWindow = null;
    }
    if (this.actions.layersWindow) {
        this.actions.layersWindow.destroy()
        this.actions.layersWindow = null;
    }
    if (this.editor != null) {
        if (this.editor.graph.overHandler) {
            this.editor.graph.overHandler.destroy()
        }

        this.editor.destroy();
        this.editor = null;
    }

    if (this.menubar != null) {
        this.menubar.destroy();
        this.menubar = null;
    }

    if (this.toolbar != null) {
        this.toolbar.destroy();
        this.toolbar = null;
    }

    if (this.sidebar != null) {
        this.sidebar.destroy();
        this.sidebar = null;
    }

    if (this.keyHandler != null) {
        this.keyHandler.destroy();
        this.keyHandler = null;
    }

    if (this.keydownHandler != null) {
        mxEvent.removeListener(document, 'keydown', this.keydownHandler);
        this.keydownHandler = null;
    }

    if (this.keyupHandler != null) {
        mxEvent.removeListener(document, 'keyup', this.keyupHandler);
        this.keyupHandler = null;
    }

    if (this.resizeHandler != null) {
        mxEvent.removeListener(window, 'resize', this.resizeHandler);
        this.resizeHandler = null;
    }

    if (this.gestureHandler != null) {
        mxEvent.removeGestureListeners(document, this.gestureHandler);
        this.gestureHandler = null;
    }

    if (this.orientationChangeHandler != null) {
        mxEvent.removeListener(window, 'orientationchange', this.orientationChangeHandler);
        this.orientationChangeHandler = null;
    }

    if (this.scrollHandler != null) {
        mxEvent.removeListener(window, 'scroll', this.scrollHandler);
        this.scrollHandler = null;
    }

    if (this.destroyFunctions != null) {
        for (var i = 0; i < this.destroyFunctions.length; i++) {
            this.destroyFunctions[i]();
        }

        this.destroyFunctions = null;
    }

    var c = [this.menubarContainer, this.toolbarContainer, this.sidebarContainer,
        this.formatContainer, this.diagramContainer, this.footerContainer,
        this.chromelessToolbar, this.hsplit, this.sidebarFooterContainer,
        this.layersDialog
    ];

    for (var i = 0; i < c.length; i++) {
        if (c[i] != null && c[i].parentNode != null) {
            c[i].parentNode.removeChild(c[i]);
        }
    }

};

/**
 * 设置工具栏值。
 * 将指定的键值对存储到背景页面的工具栏配置中。
 *
 * @param {string} key - 配置键名
 * @param {*} value - 配置值
 */
/**
 * 设置工具栏值。
 * 为指定的键设置工具栏值，用于保持工具栏状态。
 *
 * @param {string} key - 键名
 * @param {*} value - 要设置的值
 */
EditorUi.prototype.setToolbarValue = function (key, value) {
    var backgroundPage = this.editor.graph.backgroundPage
    if (!backgroundPage || !key) return;

    backgroundPage['toolbar-' + key] = value;
}

/**
 * 获取工具栏值。
 * 从背景页面的工具栏配置中获取指定键的值。
 *
 * @param {string} key - 配置键名
 * @returns {*} 配置值，如果不存在则返回null
 */
/**
 * 获取工具栏值。
 * 根据指定的键获取工具栏的值。
 *
 * @param {string} key - 键名
 * @returns {*} 工具栏的值
 */
EditorUi.prototype.getToolbarValue = function (key) {
    var backgroundPage = this.editor.graph.backgroundPage
    if (!backgroundPage || !key) return;

    return backgroundPage['toolbar-' + key] || null;
}

/**
 * 切换绘图菜单显示状态。
 * 在绘图组件和数据定义两个菜单之间切换显示状态。
 *
 * @param {Element} drawEl - 绘图组件菜单元素
 * @param {Element} defEl - 数据定义菜单元素
 */
/**
 * 切换绘图菜单。
 * 在绘图元素和默认元素之间切换显示。
 *
 * @param {Element} drawEl - 绘图元素
 * @param {Element} defEl - 默认元素
 */
EditorUi.prototype.toggleDrawingMenu = function (drawEl, defEl) {
    drawEl = drawEl || document.getElementById('gesprite-drawing-components');
    defEl = defEl || document.getElementById('gesprite-data-definition');
    var activeEl, inactiveEl;
    (!window.myEditor || window.myEditor.sidebarContainer.style.display != 'none') ? (activeEl = drawEl, inactiveEl = defEl) : (activeEl = defEl, inactiveEl = drawEl);

    activeEl.style.backgroundColor = 'rgb(250, 204, 120)';
    inactiveEl.style.backgroundColor = null;
}